blob: f624cb49f97b7bce0096ccb127663e091923b9a3 [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"
halcanarydb0dcc72015-03-20 12:31:52 -070020#include "SkPDFBitmap.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000021#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000022#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000023#include "SkPDFGraphicState.h"
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"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000036
edisonn@google.com73a7ea32013-11-11 20:55:15 +000037#define DPI_FOR_RASTER_SCALE_ONE 72
38
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000039// Utility functions
40
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000041static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000042 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
43 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000044 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000045 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
46 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000047 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000048 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
49 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000050 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000051 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
52 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000053}
54
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000055static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000056 SkPaint result = paint;
57 if (result.isFakeBoldText()) {
58 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
59 kStdFakeBoldInterpKeys,
60 kStdFakeBoldInterpValues,
61 kStdFakeBoldInterpLength);
62 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000063 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000064 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000065 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000066 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000067 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000068 result.setStrokeWidth(width);
69 }
70 return result;
71}
72
73// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000074static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000075 const uint16_t* glyphs, size_t len,
76 SkScalar* x, SkScalar* y) {
77 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000078 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000079 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080
81 SkMatrix ident;
82 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000083 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000084 SkGlyphCache* cache = autoCache.getCache();
85
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000086 const char* start = reinterpret_cast<const char*>(glyphs);
87 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000088 SkFixed xAdv = 0, yAdv = 0;
89
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000090 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000091 while (start < stop) {
92 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
93 xAdv += glyph.fAdvanceX;
94 yAdv += glyph.fAdvanceY;
95 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000096 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000097 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000098 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000099
100 SkScalar xAdj = SkFixedToScalar(xAdv);
101 SkScalar yAdj = SkFixedToScalar(yAdv);
102 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
103 xAdj = SkScalarHalf(xAdj);
104 yAdj = SkScalarHalf(yAdj);
105 }
106 *x = *x - xAdj;
107 *y = *y - yAdj;
108}
109
robertphillips@google.coma4662862013-11-21 14:24:16 +0000110static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000111 SkAutoResolveDefaultTypeface autoResolve(typeface);
112 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000113 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000114}
115
116typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
117
reed@google.comaec40662014-04-18 19:29:07 +0000118static int force_glyph_encoding(const SkPaint& paint, const void* text,
119 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700120 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000121 // Make sure we have a glyph id encoding.
122 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
reed@google.comaec40662014-04-18 19:29:07 +0000123 int numGlyphs = paint.textToGlyphs(text, len, NULL);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000124 storage->reset(numGlyphs);
125 paint.textToGlyphs(text, len, storage->get());
126 *glyphIDs = storage->get();
127 return numGlyphs;
128 }
129
130 // For user supplied glyph ids we need to validate them.
131 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000132 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700133 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000134
135 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000136 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000137 for (validated = 0; validated < numGlyphs; ++validated) {
138 if (input[validated] > maxGlyphID) {
139 break;
140 }
141 }
142 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700143 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000144 return numGlyphs;
145 }
146
147 // Silently drop anything out of range.
148 storage->reset(numGlyphs);
149 if (validated > 0) {
150 memcpy(storage->get(), input, validated * sizeof(uint16_t));
151 }
152
reed@google.comaec40662014-04-18 19:29:07 +0000153 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000154 storage->get()[i] = input[i];
155 if (input[i] > maxGlyphID) {
156 storage->get()[i] = 0;
157 }
158 }
159 *glyphIDs = storage->get();
160 return numGlyphs;
161}
162
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000163static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
164 SkWStream* content) {
165 // Flip the text about the x-axis to account for origin swap and include
166 // the passed parameters.
167 content->writeText("1 0 ");
168 SkPDFScalar::Append(0 - textSkewX, content);
169 content->writeText(" -1 ");
170 SkPDFScalar::Append(x, content);
171 content->writeText(" ");
172 SkPDFScalar::Append(y, content);
173 content->writeText(" Tm\n");
174}
175
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000176// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
177// later being our representation of an object in the PDF file.
178struct GraphicStateEntry {
179 GraphicStateEntry();
180
181 // Compare the fields we care about when setting up a new content entry.
182 bool compareInitialState(const GraphicStateEntry& b);
183
184 SkMatrix fMatrix;
185 // We can't do set operations on Paths, though PDF natively supports
186 // intersect. If the clip stack does anything other than intersect,
187 // we have to fall back to the region. Treat fClipStack as authoritative.
188 // See http://code.google.com/p/skia/issues/detail?id=221
189 SkClipStack fClipStack;
190 SkRegion fClipRegion;
191
192 // When emitting the content entry, we will ensure the graphic state
193 // is set to these values first.
194 SkColor fColor;
195 SkScalar fTextScaleX; // Zero means we don't care what the value is.
196 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
197 int fShaderIndex;
198 int fGraphicStateIndex;
199
200 // We may change the font (i.e. for Type1 support) within a
201 // ContentEntry. This is the one currently in effect, or NULL if none.
202 SkPDFFont* fFont;
203 // In PDF, text size has no default value. It is only valid if fFont is
204 // not NULL.
205 SkScalar fTextSize;
206};
207
208GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
209 fTextScaleX(SK_Scalar1),
210 fTextFill(SkPaint::kFill_Style),
211 fShaderIndex(-1),
212 fGraphicStateIndex(-1),
213 fFont(NULL),
214 fTextSize(SK_ScalarNaN) {
215 fMatrix.reset();
216}
217
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000218bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
219 return fColor == cur.fColor &&
220 fShaderIndex == cur.fShaderIndex &&
221 fGraphicStateIndex == cur.fGraphicStateIndex &&
222 fMatrix == cur.fMatrix &&
223 fClipStack == cur.fClipStack &&
224 (fTextScaleX == 0 ||
225 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000226}
227
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000228class GraphicStackState {
229public:
230 GraphicStackState(const SkClipStack& existingClipStack,
231 const SkRegion& existingClipRegion,
232 SkWStream* contentStream)
233 : fStackDepth(0),
234 fContentStream(contentStream) {
235 fEntries[0].fClipStack = existingClipStack;
236 fEntries[0].fClipRegion = existingClipRegion;
237 }
238
239 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000240 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000241 void updateMatrix(const SkMatrix& matrix);
242 void updateDrawingState(const GraphicStateEntry& state);
243
244 void drainStack();
245
246private:
247 void push();
248 void pop();
249 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
250
251 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
252 static const int kMaxStackDepth = 12;
253 GraphicStateEntry fEntries[kMaxStackDepth + 1];
254 int fStackDepth;
255 SkWStream* fContentStream;
256};
257
258void GraphicStackState::drainStack() {
259 while (fStackDepth) {
260 pop();
261 }
262}
263
264void GraphicStackState::push() {
265 SkASSERT(fStackDepth < kMaxStackDepth);
266 fContentStream->writeText("q\n");
267 fStackDepth++;
268 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
269}
270
271void GraphicStackState::pop() {
272 SkASSERT(fStackDepth > 0);
273 fContentStream->writeText("Q\n");
274 fStackDepth--;
275}
276
robertphillips@google.com80214e22012-07-20 15:33:18 +0000277// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000278// and then skips over the leading entries as specified in prefix. It requires
279// and asserts that "prefix" will be a prefix to "stack."
280static void skip_clip_stack_prefix(const SkClipStack& prefix,
281 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000282 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000283 SkClipStack::B2TIter prefixIter(prefix);
284 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000285
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000286 const SkClipStack::Element* prefixEntry;
287 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000288
289 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000290 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000291 iterEntry = iter->next();
292 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000293 // Because of SkClipStack does internal intersection, the last clip
294 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000295 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000296 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
297 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
298 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000299 // back up the iterator by one
300 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000301 prefixEntry = prefixIter.next();
302 break;
303 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000304 }
305
306 SkASSERT(prefixEntry == NULL);
307}
308
309static void emit_clip(SkPath* clipPath, SkRect* clipRect,
310 SkWStream* contentStream) {
311 SkASSERT(clipPath || clipRect);
312
313 SkPath::FillType clipFill;
314 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000315 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000316 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000317 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000318 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
319 clipFill = SkPath::kWinding_FillType;
320 }
321
322 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
323 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
324 if (clipFill == SkPath::kEvenOdd_FillType) {
325 contentStream->writeText("W* n\n");
326 } else {
327 contentStream->writeText("W n\n");
328 }
329}
330
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000331#ifdef SK_PDF_USE_PATHOPS
332/* Calculate an inverted path's equivalent non-inverted path, given the
333 * canvas bounds.
334 * outPath may alias with invPath (since this is supported by PathOps).
335 */
336static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
337 SkPath* outPath) {
338 SkASSERT(invPath.isInverseFillType());
339
340 SkPath clipPath;
341 clipPath.addRect(bounds);
342
343 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
344}
345
346// Sanity check the numerical values of the SkRegion ops and PathOps ops
347// enums so region_op_to_pathops_op can do a straight passthrough cast.
348// If these are failing, it may be necessary to make region_op_to_pathops_op
349// do more.
350SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
351 region_pathop_mismatch);
352SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
353 region_pathop_mismatch);
354SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
355 region_pathop_mismatch);
356SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
357 region_pathop_mismatch);
358SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
359 (int)kReverseDifference_PathOp,
360 region_pathop_mismatch);
361
362static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
363 SkASSERT(op >= 0);
364 SkASSERT(op <= SkRegion::kReverseDifference_Op);
365 return (SkPathOp)op;
366}
367
368/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
369 * Returns true if successful, or false if not successful.
370 * If successful, the resulting clip is stored in outClipPath.
371 * If not successful, outClipPath is undefined, and a fallback method
372 * should be used.
373 */
374static bool get_clip_stack_path(const SkMatrix& transform,
375 const SkClipStack& clipStack,
376 const SkRegion& clipRegion,
377 SkPath* outClipPath) {
378 outClipPath->reset();
379 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
380
381 const SkClipStack::Element* clipEntry;
382 SkClipStack::Iter iter;
383 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
384 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
385 SkPath entryPath;
386 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
387 outClipPath->reset();
388 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
389 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000390 } else {
391 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000392 }
393 entryPath.transform(transform);
394
395 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
396 *outClipPath = entryPath;
397 } else {
398 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
399 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
400 return false;
401 }
402 }
403 }
404
405 if (outClipPath->isInverseFillType()) {
406 // The bounds are slightly outset to ensure this is correct in the
407 // face of floating-point accuracy and possible SkRegion bitmap
408 // approximations.
409 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
410 clipBounds.outset(SK_Scalar1, SK_Scalar1);
411 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
412 return false;
413 }
414 }
415 return true;
416}
417#endif
418
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000419// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000420// graphic state stack, and the fact that we can know all the clips used
421// on the page to optimize this.
422void GraphicStackState::updateClip(const SkClipStack& clipStack,
423 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000424 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000425 if (clipStack == currentEntry()->fClipStack) {
426 return;
427 }
428
429 while (fStackDepth > 0) {
430 pop();
431 if (clipStack == currentEntry()->fClipStack) {
432 return;
433 }
434 }
435 push();
436
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000437 currentEntry()->fClipStack = clipStack;
438 currentEntry()->fClipRegion = clipRegion;
439
440 SkMatrix transform;
441 transform.setTranslate(translation.fX, translation.fY);
442
443#ifdef SK_PDF_USE_PATHOPS
444 SkPath clipPath;
445 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
446 emit_clip(&clipPath, NULL, fContentStream);
447 return;
448 }
449#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000450 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
451 // already been applied. (If this is a top level device, then it specifies
452 // a clip to the content area. If this is a layer, then it specifies
453 // the clip in effect when the layer was created.) There's no need to
454 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
455 // initial clip on the parent layer. (This means there's a bug if the user
456 // expands the clip and then uses any xfer mode that uses dst:
457 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000458 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000459 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
460
461 // If the clip stack does anything other than intersect or if it uses
462 // an inverse fill type, we have to fall back to the clip region.
463 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000464 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000465 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000466 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
467 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000468 needRegion = true;
469 break;
470 }
471 }
472
473 if (needRegion) {
474 SkPath clipPath;
475 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
476 emit_clip(&clipPath, NULL, fContentStream);
477 } else {
478 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000479 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000480 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000481 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
482 switch (clipEntry->getType()) {
483 case SkClipStack::Element::kRect_Type: {
484 SkRect translatedClip;
485 transform.mapRect(&translatedClip, clipEntry->getRect());
486 emit_clip(NULL, &translatedClip, fContentStream);
487 break;
488 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000489 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000490 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000491 clipEntry->asPath(&translatedPath);
492 translatedPath.transform(transform, &translatedPath);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000493 emit_clip(&translatedPath, NULL, fContentStream);
494 break;
495 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000496 }
497 }
498 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000499}
500
501void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
502 if (matrix == currentEntry()->fMatrix) {
503 return;
504 }
505
506 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
507 SkASSERT(fStackDepth > 0);
508 SkASSERT(fEntries[fStackDepth].fClipStack ==
509 fEntries[fStackDepth -1].fClipStack);
510 pop();
511
512 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
513 }
514 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
515 return;
516 }
517
518 push();
519 SkPDFUtils::AppendTransform(matrix, fContentStream);
520 currentEntry()->fMatrix = matrix;
521}
522
523void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
524 // PDF treats a shader as a color, so we only set one or the other.
525 if (state.fShaderIndex >= 0) {
526 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000527 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000528 currentEntry()->fShaderIndex = state.fShaderIndex;
529 }
530 } else {
531 if (state.fColor != currentEntry()->fColor ||
532 currentEntry()->fShaderIndex >= 0) {
533 emit_pdf_color(state.fColor, fContentStream);
534 fContentStream->writeText("RG ");
535 emit_pdf_color(state.fColor, fContentStream);
536 fContentStream->writeText("rg\n");
537 currentEntry()->fColor = state.fColor;
538 currentEntry()->fShaderIndex = -1;
539 }
540 }
541
542 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000543 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000544 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
545 }
546
547 if (state.fTextScaleX) {
548 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
549 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
550 SkIntToScalar(100));
551 SkPDFScalar::Append(pdfScale, fContentStream);
552 fContentStream->writeText(" Tz\n");
553 currentEntry()->fTextScaleX = state.fTextScaleX;
554 }
555 if (state.fTextFill != currentEntry()->fTextFill) {
556 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
557 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
558 enum_must_match_value);
559 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
560 enum_must_match_value);
561 fContentStream->writeDecAsText(state.fTextFill);
562 fContentStream->writeText(" Tr\n");
563 currentEntry()->fTextFill = state.fTextFill;
564 }
565 }
566}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000567
reed76033be2015-03-14 10:54:31 -0700568static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700569 // PDF does not support image filters, so render them on CPU.
570 // Note that this rendering is done at "screen" resolution (100dpi), not
571 // printer resolution.
572 // FIXME: It may be possible to express some filters natively using PDF
573 // to improve quality and file size (http://skbug.com/3043)
reed76033be2015-03-14 10:54:31 -0700574
575 // TODO: should we return true if there is a colorfilter?
576 return layerPaint.getImageFilter() != NULL;
577}
578
579SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
580 if (layerPaint && not_supported_for_layers(*layerPaint)) {
fmalita6987dca2014-11-13 08:33:37 -0800581 return SkBitmapDevice::Create(cinfo.fInfo);
senorblancob0e89dc2014-10-20 14:03:12 -0700582 }
fmalita6987dca2014-11-13 08:33:37 -0800583 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanarya1f1ee92015-02-20 06:17:26 -0800584 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000585}
586
587
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000588struct ContentEntry {
589 GraphicStateEntry fState;
590 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000591 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000592
593 // If the stack is too deep we could get Stack Overflow.
594 // So we manually destruct the object.
595 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000596 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000597 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000598 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000599 // When the destructor is called, fNext is NULL and exits.
600 delete val;
601 val = valNext;
602 }
603 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000604};
605
606// A helper class to automatically finish a ContentEntry at the end of a
607// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000608class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000609public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000610 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
611 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000612 : fDevice(device),
613 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000614 fXfermode(SkXfermode::kSrcOver_Mode),
615 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000616 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
617 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000618 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
619 const SkRegion& clipRegion, const SkMatrix& matrix,
620 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000621 : fDevice(device),
622 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000623 fXfermode(SkXfermode::kSrcOver_Mode),
624 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000625 init(clipStack, clipRegion, matrix, paint, hasText);
626 }
627
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000628 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000629 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000630 SkPath* shape = &fShape;
631 if (shape->isEmpty()) {
632 shape = NULL;
633 }
634 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000635 }
reed@google.comfc641d02012-09-20 17:52:20 +0000636 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000637 }
638
639 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000640
641 /* Returns true when we explicitly need the shape of the drawing. */
642 bool needShape() {
643 switch (fXfermode) {
644 case SkXfermode::kClear_Mode:
645 case SkXfermode::kSrc_Mode:
646 case SkXfermode::kSrcIn_Mode:
647 case SkXfermode::kSrcOut_Mode:
648 case SkXfermode::kDstIn_Mode:
649 case SkXfermode::kDstOut_Mode:
650 case SkXfermode::kSrcATop_Mode:
651 case SkXfermode::kDstATop_Mode:
652 case SkXfermode::kModulate_Mode:
653 return true;
654 default:
655 return false;
656 }
657 }
658
659 /* Returns true unless we only need the shape of the drawing. */
660 bool needSource() {
661 if (fXfermode == SkXfermode::kClear_Mode) {
662 return false;
663 }
664 return true;
665 }
666
667 /* If the shape is different than the alpha component of the content, then
668 * setShape should be called with the shape. In particular, images and
669 * devices have rectangular shape.
670 */
671 void setShape(const SkPath& shape) {
672 fShape = shape;
673 }
674
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000675private:
676 SkPDFDevice* fDevice;
677 ContentEntry* fContentEntry;
678 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000679 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000680 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000681
682 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
683 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000684 // Shape has to be flatten before we get here.
685 if (matrix.hasPerspective()) {
686 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000687 return;
688 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000689 if (paint.getXfermode()) {
690 paint.getXfermode()->asMode(&fXfermode);
691 }
692 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
693 matrix, paint, hasText,
694 &fDstFormXObject);
695 }
696};
697
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000698////////////////////////////////////////////////////////////////////////////////
699
halcanarya1f1ee92015-02-20 06:17:26 -0800700SkPDFDevice::SkPDFDevice(SkISize pageSize,
701 SkScalar rasterDpi,
702 SkPDFCanon* canon,
703 bool flip)
reed89443ab2014-06-27 11:34:19 -0700704 : fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800705 , fContentSize(pageSize)
706 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
707 , fAnnotations(NULL)
reed89443ab2014-06-27 11:34:19 -0700708 , fLastContentEntry(NULL)
709 , fLastMarginContentEntry(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800710 , fDrawingArea(kContent_DrawingArea)
reed89443ab2014-06-27 11:34:19 -0700711 , fClipStack(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800712 , fFontGlyphUsage(SkNEW(SkPDFGlyphSetMap))
713 , fRasterDpi(rasterDpi)
714 , fCanon(canon) {
715 SkASSERT(pageSize.width() > 0);
716 SkASSERT(pageSize.height() > 0);
717 fLegacyBitmap.setInfo(
718 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
719 if (flip) {
720 // Skia generally uses the top left as the origin but PDF
721 // natively has the origin at the bottom left. This matrix
722 // corrects for that. But that only needs to be done once, we
723 // don't do it when layering.
724 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
725 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
726 } else {
727 fInitialTransform.setIdentity();
728 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000729}
730
731SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000732 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000733}
734
735void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000736 fAnnotations = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000737 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000738 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000739 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000740 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000741 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000742 if (fFontGlyphUsage.get() == NULL) {
halcanary792c80f2015-02-20 07:21:05 -0800743 fFontGlyphUsage.reset(SkNEW(SkPDFGlyphSetMap));
vandebo@chromium.org98594282011-07-25 22:34:12 +0000744 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000745}
746
vandebo@chromium.org98594282011-07-25 22:34:12 +0000747void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000748 fGraphicStateResources.unrefAll();
749 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000750 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000751 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000752 SkSafeUnref(fAnnotations);
epoger@google.comb58772f2013-03-08 09:09:10 +0000753 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000754
vandebo@chromium.org98594282011-07-25 22:34:12 +0000755 if (clearFontUsage) {
756 fFontGlyphUsage->reset();
757 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000758}
759
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000760void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000761 SkPaint newPaint = paint;
762 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000763 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000764 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000765}
766
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000767void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
768 ContentEntry* contentEntry) {
769 if (!contentEntry) {
770 return;
771 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000772 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
773 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000774 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000775 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000776 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000777 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000778 inverse.mapRect(&bbox);
779
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000780 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000781 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000782 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000783}
784
785void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
786 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000787 const SkPaint& passedPaint) {
788 if (count == 0) {
789 return;
790 }
791
epoger@google.comb58772f2013-03-08 09:09:10 +0000792 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
793 return;
794 }
795
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000796 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
797 // We only use this when there's a path effect because of the overhead
798 // of multiple calls to setUpContentEntry it causes.
799 if (passedPaint.getPathEffect()) {
800 if (d.fClip->isEmpty()) {
801 return;
802 }
803 SkDraw pointDraw(d);
804 pointDraw.fDevice = this;
805 pointDraw.drawPoints(mode, count, points, passedPaint, true);
806 return;
807 }
808
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000809 const SkPaint* paint = &passedPaint;
810 SkPaint modifiedPaint;
811
812 if (mode == SkCanvas::kPoints_PointMode &&
813 paint->getStrokeCap() != SkPaint::kRound_Cap) {
814 modifiedPaint = *paint;
815 paint = &modifiedPaint;
816 if (paint->getStrokeWidth()) {
817 // PDF won't draw a single point with square/butt caps because the
818 // orientation is ambiguous. Draw a rectangle instead.
819 modifiedPaint.setStyle(SkPaint::kFill_Style);
820 SkScalar strokeWidth = paint->getStrokeWidth();
821 SkScalar halfStroke = SkScalarHalf(strokeWidth);
822 for (size_t i = 0; i < count; i++) {
823 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
824 r.inset(-halfStroke, -halfStroke);
825 drawRect(d, r, modifiedPaint);
826 }
827 return;
828 } else {
829 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
830 }
831 }
832
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000833 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000834 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000835 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000836 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000837
838 switch (mode) {
839 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000840 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000841 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000842 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000843 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000844 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000845 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000846 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000847 break;
848 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000849 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000850 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000851 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000852 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000853 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000854 &content.entry()->fContent);
855 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000856 }
857 break;
858 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000859 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
860 for (size_t i = 0; i < count; i++) {
861 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000862 &content.entry()->fContent);
863 SkPDFUtils::ClosePath(&content.entry()->fContent);
864 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000865 }
866 break;
867 default:
868 SkASSERT(false);
869 }
870}
871
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000872void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000873 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000874 SkRect r = rect;
875 r.sort();
876
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000877 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000878 if (d.fClip->isEmpty()) {
879 return;
880 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000881 SkPath path;
882 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000883 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000884 return;
885 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000886
epoger@google.comb58772f2013-03-08 09:09:10 +0000887 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000888 return;
889 }
890
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000891 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000892 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000893 return;
894 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000895 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000896 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000897 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000898}
899
reed89443ab2014-06-27 11:34:19 -0700900void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000901 SkPath path;
902 path.addRRect(rrect);
903 this->drawPath(draw, path, paint, NULL, true);
904}
905
reed89443ab2014-06-27 11:34:19 -0700906void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
907 SkPath path;
908 path.addOval(oval);
909 this->drawPath(draw, path, paint, NULL, true);
910}
911
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000912void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000913 const SkPaint& paint, const SkMatrix* prePathMatrix,
914 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000915 SkPath modifiedPath;
916 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
917
918 SkMatrix matrix = *d.fMatrix;
919 if (prePathMatrix) {
920 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
921 if (!pathIsMutable) {
922 pathPtr = &modifiedPath;
923 pathIsMutable = true;
924 }
925 origPath.transform(*prePathMatrix, pathPtr);
926 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000927 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000928 }
929 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000930
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000931 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000932 if (d.fClip->isEmpty()) {
933 return;
934 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000935 if (!pathIsMutable) {
936 pathPtr = &modifiedPath;
937 pathIsMutable = true;
938 }
939 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000940
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000941 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000942 noEffectPaint.setPathEffect(NULL);
943 if (fill) {
944 noEffectPaint.setStyle(SkPaint::kFill_Style);
945 } else {
946 noEffectPaint.setStyle(SkPaint::kStroke_Style);
947 noEffectPaint.setStrokeWidth(0);
948 }
949 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000950 return;
951 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000952
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000953#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000954 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000955 return;
956 }
957#endif
958
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000959 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000960 return;
961 }
962
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000963 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000964 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000965 return;
966 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000967 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
968 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000969 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000970 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000971}
972
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000973void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
974 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000975 const SkPaint& paint,
976 SkCanvas::DrawBitmapRectFlags flags) {
977 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000978 SkMatrix matrix;
979 SkRect bitmapBounds, tmpSrc, tmpDst;
980 SkBitmap tmpBitmap;
981
982 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
983
984 // Compute matrix from the two rectangles
985 if (src) {
986 tmpSrc = *src;
987 } else {
988 tmpSrc = bitmapBounds;
989 }
990 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
991
992 const SkBitmap* bitmapPtr = &bitmap;
993
994 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
995 // needed (if the src was clipped). No check needed if src==null.
996 if (src) {
997 if (!bitmapBounds.contains(*src)) {
998 if (!tmpSrc.intersect(bitmapBounds)) {
999 return; // nothing to draw
1000 }
1001 // recompute dst, based on the smaller tmpSrc
1002 matrix.mapRect(&tmpDst, tmpSrc);
1003 }
1004
1005 // since we may need to clamp to the borders of the src rect within
1006 // the bitmap, we extract a subset.
1007 // TODO: make sure this is handled in drawBitmap and remove from here.
1008 SkIRect srcIR;
1009 tmpSrc.roundOut(&srcIR);
1010 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1011 return;
1012 }
1013 bitmapPtr = &tmpBitmap;
1014
1015 // Since we did an extract, we need to adjust the matrix accordingly
1016 SkScalar dx = 0, dy = 0;
1017 if (srcIR.fLeft > 0) {
1018 dx = SkIntToScalar(srcIR.fLeft);
1019 }
1020 if (srcIR.fTop > 0) {
1021 dy = SkIntToScalar(srcIR.fTop);
1022 }
1023 if (dx || dy) {
1024 matrix.preTranslate(dx, dy);
1025 }
1026 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001027 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001028}
1029
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001030void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001031 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001032 if (d.fClip->isEmpty()) {
1033 return;
1034 }
1035
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001036 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001037 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001038 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1039 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001040}
1041
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001042void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001043 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001044 if (d.fClip->isEmpty()) {
1045 return;
1046 }
1047
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001048 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001049 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001050 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1051 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001052}
1053
halcanarybb264b72015-04-07 10:40:03 -07001054// Create a PDF string. Maximum length (in bytes) is 65,535.
1055// @param input A string value.
1056// @param len The length of the input array.
1057// @param wideChars True iff the upper byte in each uint16_t is
1058// significant and should be encoded and not
1059// discarded. If true, the upper byte is encoded
1060// first. Otherwise, we assert the upper byte is
1061// zero.
1062static SkString format_wide_string(const uint16_t* input,
1063 size_t len,
1064 bool wideChars) {
1065 if (wideChars) {
1066 SkASSERT(2 * len < 65535);
1067 static const char gHex[] = "0123456789ABCDEF";
1068 SkString result(4 * len + 2);
1069 result[0] = '<';
1070 for (size_t i = 0; i < len; i++) {
1071 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1072 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1073 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1074 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1075 }
1076 result[4 * len + 1] = '>';
1077 return result;
1078 } else {
1079 SkASSERT(len <= 65535);
1080 SkString tmp(len);
1081 for (size_t i = 0; i < len; i++) {
1082 SkASSERT(0 == input[i] >> 8);
1083 tmp[i] = static_cast<uint8_t>(input[i]);
1084 }
1085 return SkPDFString::FormatString(tmp.c_str(), tmp.size());
1086 }
1087}
1088
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001089void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001090 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001091 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1092 if (paint.getMaskFilter() != NULL) {
1093 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1094 // making text unreadable (e.g. same text twice when using CSS shadows).
1095 return;
1096 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001097 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001098 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001099 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001100 return;
1101 }
1102
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001103 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001104 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001105 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001106 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001107
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001108 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001109 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001110 content.entry()->fContent.writeText("BT\n");
1111 set_text_transform(x, y, textPaint.getTextSkewX(),
1112 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001113 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001114
1115 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1116
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001117 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001118 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1119 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001120
1121 int availableGlyphs = font->glyphsToPDFFontEncoding(
1122 glyphIDsCopy.begin() + consumedGlyphCount,
1123 numGlyphs - consumedGlyphCount);
1124 fFontGlyphUsage->noteGlyphUsage(
1125 font, glyphIDsCopy.begin() + consumedGlyphCount,
1126 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001127 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001128 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1129 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001130 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001131 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001132 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001133 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001134 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001135}
1136
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001137void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001138 const SkScalar pos[], int scalarsPerPos,
1139 const SkPoint& offset, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001140 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1141 if (paint.getMaskFilter() != NULL) {
1142 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1143 // making text unreadable (e.g. same text twice when using CSS shadows).
1144 return;
1145 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001146 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001147 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001148 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001149 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001150 return;
1151 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001152
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001153 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001154 const uint16_t* glyphIDs = NULL;
1155 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001156 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001157
1158 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001159 content.entry()->fContent.writeText("BT\n");
1160 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001161 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001162 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001163 uint16_t encodedValue = glyphIDs[i];
1164 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001165 // The current pdf font cannot encode the current glyph.
1166 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001167 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001168 font = content.entry()->fState.fFont;
1169 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1170 SkDEBUGFAIL("PDF could not encode glyph.");
1171 continue;
1172 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001173 }
bungeman22edc832014-10-03 07:55:58 -07001174
vandebo@chromium.org98594282011-07-25 22:34:12 +00001175 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001176 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1177 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1178
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001179 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001180 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001181 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001182 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001183 content.entry()->fContent.writeText(encodedString.c_str());
1184 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001185 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001186 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001187}
1188
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001189void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001190 int vertexCount, const SkPoint verts[],
1191 const SkPoint texs[], const SkColor colors[],
1192 SkXfermode* xmode, const uint16_t indices[],
1193 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001194 if (d.fClip->isEmpty()) {
1195 return;
1196 }
reed@google.com85e143c2013-12-30 15:51:25 +00001197 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001198}
1199
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001200void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1201 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001202 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001203 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001204 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001205 return;
1206 }
1207
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001208 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001209 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001210 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001211 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001212 return;
1213 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001214 if (content.needShape()) {
1215 SkPath shape;
1216 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001217 SkIntToScalar(device->width()),
1218 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001219 content.setShape(shape);
1220 }
1221 if (!content.needSource()) {
1222 return;
1223 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001224
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001225 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1226 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001227 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001228
1229 // Merge glyph sets from the drawn device.
1230 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001231}
1232
reed89443ab2014-06-27 11:34:19 -07001233SkImageInfo SkPDFDevice::imageInfo() const {
1234 return fLegacyBitmap.info();
1235}
1236
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001237void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1238 INHERITED::onAttachToCanvas(canvas);
1239
1240 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1241 fClipStack = canvas->getClipStack();
1242}
1243
1244void SkPDFDevice::onDetachFromCanvas() {
1245 INHERITED::onDetachFromCanvas();
1246
1247 fClipStack = NULL;
1248}
1249
reed4a8126e2014-09-22 07:29:03 -07001250SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1251 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001252}
1253
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001254ContentEntry* SkPDFDevice::getLastContentEntry() {
1255 if (fDrawingArea == kContent_DrawingArea) {
1256 return fLastContentEntry;
1257 } else {
1258 return fLastMarginContentEntry;
1259 }
1260}
1261
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001262SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001263 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001264 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001265 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001266 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001267 }
1268}
1269
1270void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1271 if (fDrawingArea == kContent_DrawingArea) {
1272 fLastContentEntry = contentEntry;
1273 } else {
1274 fLastMarginContentEntry = contentEntry;
1275 }
1276}
1277
1278void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001279 // A ScopedContentEntry only exists during the course of a draw call, so
1280 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001281 fDrawingArea = drawingArea;
1282}
1283
halcanary6d622702015-03-25 08:45:42 -07001284SkPDFResourceDict* SkPDFDevice::createResourceDict() const {
1285 SkAutoTUnref<SkPDFResourceDict> resourceDict(SkNEW(SkPDFResourceDict));
1286 if (fGraphicStateResources.count()) {
1287 for (int i = 0; i < fGraphicStateResources.count(); i++) {
1288 resourceDict->insertResourceAsReference(
1289 SkPDFResourceDict::kExtGState_ResourceType,
1290 i, fGraphicStateResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001291 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001292 }
halcanary6d622702015-03-25 08:45:42 -07001293
1294 if (fXObjectResources.count()) {
1295 for (int i = 0; i < fXObjectResources.count(); i++) {
1296 resourceDict->insertResourceAsReference(
1297 SkPDFResourceDict::kXObject_ResourceType,
1298 i, fXObjectResources[i]);
1299 }
1300 }
1301
1302 if (fFontResources.count()) {
1303 for (int i = 0; i < fFontResources.count(); i++) {
1304 resourceDict->insertResourceAsReference(
1305 SkPDFResourceDict::kFont_ResourceType,
1306 i, fFontResources[i]);
1307 }
1308 }
1309
1310 if (fShaderResources.count()) {
1311 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
1312 for (int i = 0; i < fShaderResources.count(); i++) {
1313 resourceDict->insertResourceAsReference(
1314 SkPDFResourceDict::kPattern_ResourceType,
1315 i, fShaderResources[i]);
1316 }
1317 }
1318 return resourceDict.detach();
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001319}
1320
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001321const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1322 return fFontResources;
1323}
1324
reed@google.com2a006c12012-09-19 17:05:55 +00001325SkPDFArray* SkPDFDevice::copyMediaBox() const {
1326 // should this be a singleton?
1327 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001328
reed@google.com2a006c12012-09-19 17:05:55 +00001329 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001330 mediaBox->reserve(4);
1331 mediaBox->append(zero.get());
1332 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001333 mediaBox->appendInt(fPageSize.fWidth);
1334 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001335 return mediaBox;
1336}
1337
halcanary334fcbc2015-02-24 12:56:16 -08001338SkStreamAsset* SkPDFDevice::content() const {
1339 SkDynamicMemoryWStream buffer;
1340 this->writeContent(&buffer);
1341 return buffer.detachAsStream();
reed@google.com5667afc2011-06-27 14:42:15 +00001342}
1343
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001344void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1345 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001346 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1347 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001348 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001349 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001350 SkPoint translation;
1351 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001352 translation.negate();
1353 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1354 translation);
1355 gsState.updateMatrix(entry->fState.fMatrix);
1356 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001357
halcanary7af21502015-02-23 12:17:59 -08001358 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001359 entry = entry->fNext.get();
1360 }
1361 gsState.drainStack();
1362}
1363
halcanary334fcbc2015-02-24 12:56:16 -08001364void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001365 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001366 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001367 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001368
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001369 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1370 // colors the contentArea white before it starts drawing into it and
1371 // that currently acts as our clip.
1372 // Also, think about adding a transform here (or assume that the values
1373 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001374 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001375
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001376 // If the content area is the entire page, then we don't need to clip
1377 // the content area (PDF area clips to the page size). Otherwise,
1378 // we have to clip to the content area; we've already applied the
1379 // initial transform, so just clip to the device size.
1380 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001381 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1382 SkIntToScalar(this->height()));
halcanary334fcbc2015-02-24 12:56:16 -08001383 emit_clip(NULL, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001384 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001385
halcanary334fcbc2015-02-24 12:56:16 -08001386 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001387}
1388
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001389#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001390/* Draws an inverse filled path by using Path Ops to compute the positive
1391 * inverse using the current clip as the inverse bounds.
1392 * Return true if this was an inverse path and was properly handled,
1393 * otherwise returns false and the normal drawing routine should continue,
1394 * either as a (incorrect) fallback or because the path was not inverse
1395 * in the first place.
1396 */
1397bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001398 const SkPaint& paint, bool pathIsMutable,
1399 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001400 if (!origPath.isInverseFillType()) {
1401 return false;
1402 }
1403
1404 if (d.fClip->isEmpty()) {
1405 return false;
1406 }
1407
1408 SkPath modifiedPath;
1409 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1410 SkPaint noInversePaint(paint);
1411
1412 // Merge stroking operations into final path.
1413 if (SkPaint::kStroke_Style == paint.getStyle() ||
1414 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1415 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1416 if (doFillPath) {
1417 noInversePaint.setStyle(SkPaint::kFill_Style);
1418 noInversePaint.setStrokeWidth(0);
1419 pathPtr = &modifiedPath;
1420 } else {
1421 // To be consistent with the raster output, hairline strokes
1422 // are rendered as non-inverted.
1423 modifiedPath.toggleInverseFillType();
1424 drawPath(d, modifiedPath, paint, NULL, true);
1425 return true;
1426 }
1427 }
1428
1429 // Get bounds of clip in current transform space
1430 // (clip bounds are given in device space).
1431 SkRect bounds;
1432 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001433 SkMatrix totalMatrix = *d.fMatrix;
1434 if (prePathMatrix) {
1435 totalMatrix.preConcat(*prePathMatrix);
1436 }
1437 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001438 return false;
1439 }
1440 bounds.set(d.fClip->getBounds());
1441 transformInverse.mapRect(&bounds);
1442
1443 // Extend the bounds by the line width (plus some padding)
1444 // so the edge doesn't cause a visible stroke.
1445 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1446 paint.getStrokeWidth() + SK_Scalar1);
1447
1448 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1449 return false;
1450 }
1451
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001452 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001453 return true;
1454}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001455#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001456
epoger@google.comb58772f2013-03-08 09:09:10 +00001457bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1458 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001459 SkAnnotation* annotationInfo = p.getAnnotation();
1460 if (!annotationInfo) {
1461 return false;
1462 }
1463 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001464 if (urlData) {
1465 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001466 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001467 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001468 SkData* linkToName = annotationInfo->find(
1469 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001470 if (linkToName) {
1471 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001472 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001473 }
1474 return false;
1475}
1476
1477bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1478 const SkMatrix& matrix,
1479 const SkPaint& paint) {
1480 SkAnnotation* annotationInfo = paint.getAnnotation();
1481 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001482 return false;
1483 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001484 SkData* nameData = annotationInfo->find(
1485 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001486 if (nameData) {
1487 for (size_t i = 0; i < count; i++) {
1488 defineNamedDestination(nameData, points[i], matrix);
1489 }
reed@google.com44699382013-10-31 17:28:30 +00001490 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001491 }
1492 return false;
1493}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001494
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001495SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1496 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001497 SkMatrix transform = matrix;
1498 transform.postConcat(fInitialTransform);
1499 SkRect translatedRect;
1500 transform.mapRect(&translatedRect, r);
1501
reed@google.com2a006c12012-09-19 17:05:55 +00001502 if (NULL == fAnnotations) {
1503 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001504 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001505 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001506 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001507 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001508
epoger@google.comb58772f2013-03-08 09:09:10 +00001509 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001510 border->reserve(3);
1511 border->appendInt(0); // Horizontal corner radius.
1512 border->appendInt(0); // Vertical corner radius.
1513 border->appendInt(0); // Width, 0 = no border.
1514 annotation->insert("Border", border.get());
1515
epoger@google.comb58772f2013-03-08 09:09:10 +00001516 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001517 rect->reserve(4);
1518 rect->appendScalar(translatedRect.fLeft);
1519 rect->appendScalar(translatedRect.fTop);
1520 rect->appendScalar(translatedRect.fRight);
1521 rect->appendScalar(translatedRect.fBottom);
1522 annotation->insert("Rect", rect.get());
1523
epoger@google.comb58772f2013-03-08 09:09:10 +00001524 return annotation;
1525}
epoger@google.com1cad8982013-03-06 00:05:13 +00001526
epoger@google.comb58772f2013-03-08 09:09:10 +00001527void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1528 const SkMatrix& matrix) {
1529 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1530
1531 SkString url(static_cast<const char *>(urlData->data()),
1532 urlData->size() - 1);
1533 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1534 action->insertName("S", "URI");
1535 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1536 annotation->insert("A", action.get());
1537}
1538
1539void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1540 const SkMatrix& matrix) {
1541 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1542 SkString name(static_cast<const char *>(nameData->data()),
1543 nameData->size() - 1);
1544 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1545}
1546
1547struct NamedDestination {
1548 const SkData* nameData;
1549 SkPoint point;
1550
1551 NamedDestination(const SkData* nameData, const SkPoint& point)
1552 : nameData(nameData), point(point) {
1553 nameData->ref();
1554 }
1555
1556 ~NamedDestination() {
1557 nameData->unref();
1558 }
1559};
1560
1561void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1562 const SkMatrix& matrix) {
1563 SkMatrix transform = matrix;
1564 transform.postConcat(fInitialTransform);
1565 SkPoint translatedPoint;
1566 transform.mapXY(point.x(), point.y(), &translatedPoint);
1567 fNamedDestinations.push(
1568 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1569}
1570
halcanary6d622702015-03-25 08:45:42 -07001571void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
epoger@google.comb58772f2013-03-08 09:09:10 +00001572 int nDest = fNamedDestinations.count();
1573 for (int i = 0; i < nDest; i++) {
1574 NamedDestination* dest = fNamedDestinations[i];
1575 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1576 pdfDest->reserve(5);
1577 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1578 pdfDest->appendName("XYZ");
1579 pdfDest->appendScalar(dest->point.x());
1580 pdfDest->appendScalar(dest->point.y());
1581 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001582 dict->insert(static_cast<const char *>(dest->nameData->data()),
1583 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001584 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001585}
1586
reed@google.comfc641d02012-09-20 17:52:20 +00001587SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1588 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001589 // We always draw the form xobjects that we create back into the device, so
1590 // we simply preserve the font usage instead of pulling it out and merging
1591 // it back in later.
1592 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001593 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001594 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001595}
1596
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001597void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1598 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001599 const SkClipStack* clipStack,
1600 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001601 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001602 bool invertClip) {
1603 if (clipRegion.isEmpty() && !invertClip) {
1604 return;
1605 }
1606
halcanarybe27a112015-04-01 13:31:19 -07001607 SkAutoTUnref<SkPDFObject> sMaskGS(SkPDFGraphicState::GetSMaskGraphicState(
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001608 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1609
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001610 SkMatrix identity;
1611 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001612 SkPaint paint;
1613 paint.setXfermodeMode(mode);
1614 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001615 if (!content.entry()) {
1616 return;
1617 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001618 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001619 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001620 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001621
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001622 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001623 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001624 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001625}
1626
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001627ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1628 const SkRegion& clipRegion,
1629 const SkMatrix& matrix,
1630 const SkPaint& paint,
1631 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001632 SkPDFFormXObject** dst) {
1633 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001634 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001635 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001636 }
1637
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001638 // The clip stack can come from an SkDraw where it is technically optional.
1639 SkClipStack synthesizedClipStack;
1640 if (clipStack == NULL) {
1641 if (clipRegion == fExistingClipRegion) {
1642 clipStack = &fExistingClipStack;
1643 } else {
1644 // GraphicStackState::updateClip expects the clip stack to have
1645 // fExistingClip as a prefix, so start there, then set the clip
1646 // to the passed region.
1647 synthesizedClipStack = fExistingClipStack;
1648 SkPath clipPath;
1649 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001650 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1651 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001652 clipStack = &synthesizedClipStack;
1653 }
1654 }
1655
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001656 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1657 if (paint.getXfermode()) {
1658 paint.getXfermode()->asMode(&xfermode);
1659 }
1660
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001661 // For the following modes, we want to handle source and destination
1662 // separately, so make an object of what's already there.
1663 if (xfermode == SkXfermode::kClear_Mode ||
1664 xfermode == SkXfermode::kSrc_Mode ||
1665 xfermode == SkXfermode::kSrcIn_Mode ||
1666 xfermode == SkXfermode::kDstIn_Mode ||
1667 xfermode == SkXfermode::kSrcOut_Mode ||
1668 xfermode == SkXfermode::kDstOut_Mode ||
1669 xfermode == SkXfermode::kSrcATop_Mode ||
1670 xfermode == SkXfermode::kDstATop_Mode ||
1671 xfermode == SkXfermode::kModulate_Mode) {
1672 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001673 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001674 SkASSERT(isContentEmpty());
1675 } else if (xfermode != SkXfermode::kSrc_Mode &&
1676 xfermode != SkXfermode::kSrcOut_Mode) {
1677 // Except for Src and SrcOut, if there isn't anything already there,
1678 // then we're done.
1679 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001680 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001681 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001682 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001683 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001684
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001685 // Dst xfer mode doesn't draw source at all.
1686 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001687 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001688 }
1689
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001690 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001691 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001692
1693 ContentEntry* lastContentEntry = getLastContentEntry();
1694 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1695 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001696 } else {
1697 newEntry.reset(new ContentEntry);
1698 entry = newEntry.get();
1699 }
1700
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001701 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001702 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001703 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1704 entry->fState.compareInitialState(lastContentEntry->fState)) {
1705 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001706 }
1707
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001708 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001709 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001710 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001711 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001712 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001713 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001714 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001715 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001716 lastContentEntry->fNext.reset(entry);
1717 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001718 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001719 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001720 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001721}
1722
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001723void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001724 SkPDFFormXObject* dst,
1725 SkPath* shape) {
1726 if (xfermode != SkXfermode::kClear_Mode &&
1727 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001728 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001729 xfermode != SkXfermode::kSrcIn_Mode &&
1730 xfermode != SkXfermode::kDstIn_Mode &&
1731 xfermode != SkXfermode::kSrcOut_Mode &&
1732 xfermode != SkXfermode::kDstOut_Mode &&
1733 xfermode != SkXfermode::kSrcATop_Mode &&
1734 xfermode != SkXfermode::kDstATop_Mode &&
1735 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001736 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001737 return;
1738 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001739 if (xfermode == SkXfermode::kDstOver_Mode) {
1740 SkASSERT(!dst);
1741 ContentEntry* firstContentEntry = getContentEntries()->get();
1742 if (firstContentEntry->fContent.getOffset() == 0) {
1743 // For DstOver, an empty content entry was inserted before the rest
1744 // of the content entries. If nothing was drawn, it needs to be
1745 // removed.
1746 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1747 contentEntries->reset(firstContentEntry->fNext.detach());
1748 }
1749 return;
1750 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001751 if (!dst) {
1752 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1753 xfermode == SkXfermode::kSrcOut_Mode);
1754 return;
1755 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001756
1757 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001758 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001759 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001760 // Changing the current content into a form-xobject will destroy the clip
1761 // objects which is fine since the xobject will already be clipped. However
1762 // if source has shape, we need to clip it too, so a copy of the clip is
1763 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001764 SkClipStack clipStack = contentEntries->fState.fClipStack;
1765 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001766
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001767 SkMatrix identity;
1768 identity.reset();
1769 SkPaint stockPaint;
1770
reed@google.comfc641d02012-09-20 17:52:20 +00001771 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001772 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001773 // If nothing was drawn and there's no shape, then the draw was a
1774 // no-op, but dst needs to be restored for that to be true.
1775 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1776 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1777 // reduces to Dst.
1778 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1779 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001780 ScopedContentEntry content(this, &fExistingClipStack,
1781 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001782 stockPaint);
1783 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1784 &content.entry()->fContent);
1785 return;
1786 } else {
1787 xfermode = SkXfermode::kClear_Mode;
1788 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001789 } else {
1790 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001791 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001792 }
1793
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001794 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1795 // without alpha.
1796 if (xfermode == SkXfermode::kSrcATop_Mode) {
1797 // TODO(vandebo): In order to properly support SrcATop we have to track
1798 // the shape of what's been drawn at all times. It's the intersection of
1799 // the non-transparent parts of the device and the outlines (shape) of
1800 // all images and devices drawn.
1801 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001802 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001803 SkXfermode::kSrcOver_Mode, true);
1804 } else {
1805 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1806 SkPDFFormXObject* dstMask = srcFormXObject.get();
1807 if (shape != NULL) {
1808 // Draw shape into a form-xobject.
1809 SkDraw d;
1810 d.fMatrix = &identity;
1811 d.fClip = &clipRegion;
1812 d.fClipStack = &clipStack;
1813 SkPaint filledPaint;
1814 filledPaint.setColor(SK_ColorBLACK);
1815 filledPaint.setStyle(SkPaint::kFill_Style);
1816 this->drawPath(d, *shape, filledPaint, NULL, true);
1817
1818 dstMaskStorage.reset(createFormXObjectFromDevice());
1819 dstMask = dstMaskStorage.get();
1820 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001821 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1822 &fExistingClipStack, fExistingClipRegion,
1823 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001824 }
1825
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001826 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001827 return;
1828 } else if (xfermode == SkXfermode::kSrc_Mode ||
1829 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001830 ScopedContentEntry content(this, &fExistingClipStack,
1831 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001832 if (content.entry()) {
1833 SkPDFUtils::DrawFormXObject(
1834 this->addXObjectResource(srcFormXObject.get()),
1835 &content.entry()->fContent);
1836 }
1837 if (xfermode == SkXfermode::kSrc_Mode) {
1838 return;
1839 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001840 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001841 ScopedContentEntry content(this, &fExistingClipStack,
1842 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001843 if (content.entry()) {
1844 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1845 &content.entry()->fContent);
1846 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001847 }
1848
1849 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1850 xfermode == SkXfermode::kDstIn_Mode ||
1851 xfermode == SkXfermode::kSrcOut_Mode ||
1852 xfermode == SkXfermode::kDstOut_Mode ||
1853 xfermode == SkXfermode::kSrcATop_Mode ||
1854 xfermode == SkXfermode::kDstATop_Mode ||
1855 xfermode == SkXfermode::kModulate_Mode);
1856
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001857 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001858 xfermode == SkXfermode::kSrcOut_Mode ||
1859 xfermode == SkXfermode::kSrcATop_Mode) {
1860 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001861 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001862 SkXfermode::kSrcOver_Mode,
1863 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001864 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001865 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1866 if (xfermode == SkXfermode::kModulate_Mode) {
1867 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001868 dst, &fExistingClipStack,
1869 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001870 SkXfermode::kSrcOver_Mode, false);
1871 mode = SkXfermode::kMultiply_Mode;
1872 }
1873 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001874 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001875 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001876 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001877}
1878
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001879bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001880 ContentEntry* contentEntries = getContentEntries()->get();
1881 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1882 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001883 return true;
1884 }
1885 return false;
1886}
1887
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001888void SkPDFDevice::populateGraphicStateEntryFromPaint(
1889 const SkMatrix& matrix,
1890 const SkClipStack& clipStack,
1891 const SkRegion& clipRegion,
1892 const SkPaint& paint,
1893 bool hasText,
1894 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001895 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001896 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1897 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001898
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001899 entry->fMatrix = matrix;
1900 entry->fClipStack = clipStack;
1901 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001902 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1903 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001904
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001905 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001906 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001907 const SkShader* shader = paint.getShader();
1908 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001909 if (shader) {
1910 // PDF positions patterns relative to the initial transform, so
1911 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001912 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001913 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001914
1915 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001916 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001917 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001918
1919 // We need to apply the initial transform to bounds in order to get
1920 // bounds in a consistent coordinate system.
1921 SkRect boundsTemp;
1922 boundsTemp.set(bounds);
1923 fInitialTransform.mapRect(&boundsTemp);
1924 boundsTemp.roundOut(&bounds);
1925
halcanary792c80f2015-02-20 07:21:05 -08001926 SkScalar rasterScale =
1927 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
1928 pdfShader.reset(SkPDFShader::GetPDFShader(
1929 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001930
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001931 if (pdfShader.get()) {
1932 // pdfShader has been canonicalized so we can directly compare
1933 // pointers.
1934 int resourceIndex = fShaderResources.find(pdfShader.get());
1935 if (resourceIndex < 0) {
1936 resourceIndex = fShaderResources.count();
1937 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001938 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001939 }
1940 entry->fShaderIndex = resourceIndex;
1941 } else {
1942 // A color shader is treated as an invalid shader so we don't have
1943 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001944 SkShader::GradientInfo gradientInfo;
1945 SkColor gradientColor;
1946 gradientInfo.fColors = &gradientColor;
1947 gradientInfo.fColorOffsets = NULL;
1948 gradientInfo.fColorCount = 1;
1949 if (shader->asAGradient(&gradientInfo) ==
1950 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001951 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1952 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001953 }
1954 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001955 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001956
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001957 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001958 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001959 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001960 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001961 } else {
1962 SkPaint newPaint = paint;
1963 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001964 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001965 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001966 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001967 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001968 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001969
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001970 if (hasText) {
1971 entry->fTextScaleX = paint.getTextScaleX();
1972 entry->fTextFill = paint.getStyle();
1973 } else {
1974 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001975 }
1976}
1977
halcanarybe27a112015-04-01 13:31:19 -07001978int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001979 // Assumes that gs has been canonicalized (so we can directly compare
1980 // pointers).
1981 int result = fGraphicStateResources.find(gs);
1982 if (result < 0) {
1983 result = fGraphicStateResources.count();
1984 fGraphicStateResources.push(gs);
1985 gs->ref();
1986 }
1987 return result;
1988}
1989
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001990int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
1991 // Assumes that xobject has been canonicalized (so we can directly compare
1992 // pointers).
1993 int result = fXObjectResources.find(xObject);
1994 if (result < 0) {
1995 result = fXObjectResources.count();
1996 fXObjectResources.push(xObject);
1997 xObject->ref();
1998 }
1999 return result;
2000}
2001
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002002void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2003 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002004 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002005 if (contentEntry->fState.fFont == NULL ||
2006 contentEntry->fState.fTextSize != paint.getTextSize() ||
2007 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002008 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002009 contentEntry->fContent.writeText("/");
2010 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2011 SkPDFResourceDict::kFont_ResourceType,
2012 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002013 contentEntry->fContent.writeText(" ");
2014 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2015 contentEntry->fContent.writeText(" Tf\n");
2016 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002017 }
2018}
2019
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002020int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary792c80f2015-02-20 07:21:05 -08002021 SkAutoTUnref<SkPDFFont> newFont(
2022 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002023 int resourceIndex = fFontResources.find(newFont.get());
2024 if (resourceIndex < 0) {
2025 resourceIndex = fFontResources.count();
2026 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002027 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002028 }
2029 return resourceIndex;
2030}
2031
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002032void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002033 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002034 const SkRegion& origClipRegion,
2035 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002036 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002037 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002038 SkMatrix matrix = origMatrix;
2039 SkRegion perspectiveBounds;
2040 const SkRegion* clipRegion = &origClipRegion;
2041 SkBitmap perspectiveBitmap;
2042 const SkBitmap* bitmap = &origBitmap;
2043 SkBitmap tmpSubsetBitmap;
2044
2045 // Rasterize the bitmap using perspective in a new bitmap.
2046 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002047 if (fRasterDpi == 0) {
2048 return;
2049 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002050 SkBitmap* subsetBitmap;
2051 if (srcRect) {
2052 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2053 return;
2054 }
2055 subsetBitmap = &tmpSubsetBitmap;
2056 } else {
2057 subsetBitmap = &tmpSubsetBitmap;
2058 *subsetBitmap = origBitmap;
2059 }
2060 srcRect = NULL;
2061
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002062 // Transform the bitmap in the new space, without taking into
2063 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002064 SkPath perspectiveOutline;
2065 perspectiveOutline.addRect(
2066 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2067 SkIntToScalar(subsetBitmap->height())));
2068 perspectiveOutline.transform(origMatrix);
2069
2070 // TODO(edisonn): perf - use current clip too.
2071 // Retrieve the bounds of the new shape.
2072 SkRect bounds = perspectiveOutline.getBounds();
2073
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002074 // Transform the bitmap in the new space, taking into
2075 // account the initial transform.
2076 SkMatrix total = origMatrix;
2077 total.postConcat(fInitialTransform);
2078 total.postScale(SkIntToScalar(fRasterDpi) /
2079 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2080 SkIntToScalar(fRasterDpi) /
2081 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2082 SkPath physicalPerspectiveOutline;
2083 physicalPerspectiveOutline.addRect(
2084 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2085 SkIntToScalar(subsetBitmap->height())));
2086 physicalPerspectiveOutline.transform(total);
2087
2088 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2089 bounds.width();
2090 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2091 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002092
2093 // TODO(edisonn): A better approach would be to use a bitmap shader
2094 // (in clamp mode) and draw a rect over the entire bounding box. Then
2095 // intersect perspectiveOutline to the clip. That will avoid introducing
2096 // alpha to the image while still giving good behavior at the edge of
2097 // the image. Avoiding alpha will reduce the pdf size and generation
2098 // CPU time some.
2099
reed@google.com9ebcac52014-01-24 18:53:42 +00002100 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2101 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002102 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002103 return;
2104 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002105 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2106
reed89443ab2014-06-27 11:34:19 -07002107 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002108
2109 SkScalar deltaX = bounds.left();
2110 SkScalar deltaY = bounds.top();
2111
2112 SkMatrix offsetMatrix = origMatrix;
2113 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002114 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002115
2116 // Translate the draw in the new canvas, so we perfectly fit the
2117 // shape in the bitmap.
2118 canvas.setMatrix(offsetMatrix);
2119
2120 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2121
2122 // Make sure the final bits are in the bitmap.
2123 canvas.flush();
2124
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002125 // In the new space, we use the identity matrix translated
2126 // and scaled to reflect DPI.
2127 matrix.setScale(1 / scaleX, 1 / scaleY);
2128 matrix.postTranslate(deltaX, deltaY);
2129
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002130 perspectiveBounds.setRect(
2131 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2132 SkScalarFloorToInt(bounds.y()),
2133 SkScalarCeilToInt(bounds.width()),
2134 SkScalarCeilToInt(bounds.height())));
2135 clipRegion = &perspectiveBounds;
2136 srcRect = NULL;
2137 bitmap = &perspectiveBitmap;
2138 }
2139
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002140 SkMatrix scaled;
2141 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002142 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2143 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002144 // Scale the image up from 1x1 to WxH.
halcanaryf622a6c2014-10-24 12:54:53 -07002145 SkIRect subset = bitmap->bounds();
reed@google.coma6d59f62011-03-07 21:29:21 +00002146 scaled.postScale(SkIntToScalar(subset.width()),
2147 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002148 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002149 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002150 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2151 return;
2152 }
2153 if (content.needShape()) {
2154 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002155 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
halcanarydb0dcc72015-03-20 12:31:52 -07002156 SkIntToScalar(subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002157 shape.transform(matrix);
2158 content.setShape(shape);
2159 }
2160 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002161 return;
2162 }
2163
halcanarydb0dcc72015-03-20 12:31:52 -07002164 SkBitmap subsetBitmap;
2165 // Should extractSubset be done by the SkPDFDevice?
2166 if (!bitmap->extractSubset(&subsetBitmap, subset)) {
2167 return;
2168 }
2169 SkAutoTUnref<SkPDFObject> image(SkPDFBitmap::Create(fCanon, subsetBitmap));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002170 if (!image) {
2171 return;
2172 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002173
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002174 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002175 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002176}