blob: b08bb174b1638ad477bc8b023d2e8f03f91766f5 [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/* Calculate an inverted path's equivalent non-inverted path, given the
332 * canvas bounds.
333 * outPath may alias with invPath (since this is supported by PathOps).
334 */
335static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
336 SkPath* outPath) {
337 SkASSERT(invPath.isInverseFillType());
338
339 SkPath clipPath;
340 clipPath.addRect(bounds);
341
342 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
343}
344
fmalita632e92f2015-04-22 15:02:03 -0700345#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000346// 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
fmalita632e92f2015-04-22 15:02:03 -0700443#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000444 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) {
halcanary00b7e5e2015-04-15 13:05:18 -0700580 if (cinfo.fForImageFilter ||
581 (layerPaint && not_supported_for_layers(*layerPaint))) {
fmalita6987dca2014-11-13 08:33:37 -0800582 return SkBitmapDevice::Create(cinfo.fInfo);
senorblancob0e89dc2014-10-20 14:03:12 -0700583 }
fmalita6987dca2014-11-13 08:33:37 -0800584 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanarya1f1ee92015-02-20 06:17:26 -0800585 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000586}
587
588
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000589struct ContentEntry {
590 GraphicStateEntry fState;
591 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000592 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000593
594 // If the stack is too deep we could get Stack Overflow.
595 // So we manually destruct the object.
596 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000597 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000598 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000599 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000600 // When the destructor is called, fNext is NULL and exits.
601 delete val;
602 val = valNext;
603 }
604 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000605};
606
607// A helper class to automatically finish a ContentEntry at the end of a
608// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000609class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000610public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000611 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
612 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000613 : fDevice(device),
614 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000615 fXfermode(SkXfermode::kSrcOver_Mode),
616 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000617 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
618 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000619 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
620 const SkRegion& clipRegion, const SkMatrix& matrix,
621 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000622 : fDevice(device),
623 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000624 fXfermode(SkXfermode::kSrcOver_Mode),
625 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000626 init(clipStack, clipRegion, matrix, paint, hasText);
627 }
628
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000629 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000630 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000631 SkPath* shape = &fShape;
632 if (shape->isEmpty()) {
633 shape = NULL;
634 }
635 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000636 }
reed@google.comfc641d02012-09-20 17:52:20 +0000637 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000638 }
639
640 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000641
642 /* Returns true when we explicitly need the shape of the drawing. */
643 bool needShape() {
644 switch (fXfermode) {
645 case SkXfermode::kClear_Mode:
646 case SkXfermode::kSrc_Mode:
647 case SkXfermode::kSrcIn_Mode:
648 case SkXfermode::kSrcOut_Mode:
649 case SkXfermode::kDstIn_Mode:
650 case SkXfermode::kDstOut_Mode:
651 case SkXfermode::kSrcATop_Mode:
652 case SkXfermode::kDstATop_Mode:
653 case SkXfermode::kModulate_Mode:
654 return true;
655 default:
656 return false;
657 }
658 }
659
660 /* Returns true unless we only need the shape of the drawing. */
661 bool needSource() {
662 if (fXfermode == SkXfermode::kClear_Mode) {
663 return false;
664 }
665 return true;
666 }
667
668 /* If the shape is different than the alpha component of the content, then
669 * setShape should be called with the shape. In particular, images and
670 * devices have rectangular shape.
671 */
672 void setShape(const SkPath& shape) {
673 fShape = shape;
674 }
675
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000676private:
677 SkPDFDevice* fDevice;
678 ContentEntry* fContentEntry;
679 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000680 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000681 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000682
683 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
684 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000685 // Shape has to be flatten before we get here.
686 if (matrix.hasPerspective()) {
687 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000688 return;
689 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000690 if (paint.getXfermode()) {
691 paint.getXfermode()->asMode(&fXfermode);
692 }
693 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
694 matrix, paint, hasText,
695 &fDstFormXObject);
696 }
697};
698
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000699////////////////////////////////////////////////////////////////////////////////
700
halcanarya1f1ee92015-02-20 06:17:26 -0800701SkPDFDevice::SkPDFDevice(SkISize pageSize,
702 SkScalar rasterDpi,
703 SkPDFCanon* canon,
704 bool flip)
reed89443ab2014-06-27 11:34:19 -0700705 : fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800706 , fContentSize(pageSize)
707 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
708 , fAnnotations(NULL)
reed89443ab2014-06-27 11:34:19 -0700709 , fLastContentEntry(NULL)
710 , fLastMarginContentEntry(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800711 , fDrawingArea(kContent_DrawingArea)
reed89443ab2014-06-27 11:34:19 -0700712 , fClipStack(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800713 , fFontGlyphUsage(SkNEW(SkPDFGlyphSetMap))
714 , fRasterDpi(rasterDpi)
715 , fCanon(canon) {
716 SkASSERT(pageSize.width() > 0);
717 SkASSERT(pageSize.height() > 0);
718 fLegacyBitmap.setInfo(
719 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
720 if (flip) {
721 // Skia generally uses the top left as the origin but PDF
722 // natively has the origin at the bottom left. This matrix
723 // corrects for that. But that only needs to be done once, we
724 // don't do it when layering.
725 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
726 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
727 } else {
728 fInitialTransform.setIdentity();
729 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000730}
731
732SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000733 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000734}
735
736void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000737 fAnnotations = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000738 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000739 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000740 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000741 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000742 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000743 if (fFontGlyphUsage.get() == NULL) {
halcanary792c80f2015-02-20 07:21:05 -0800744 fFontGlyphUsage.reset(SkNEW(SkPDFGlyphSetMap));
vandebo@chromium.org98594282011-07-25 22:34:12 +0000745 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000746}
747
vandebo@chromium.org98594282011-07-25 22:34:12 +0000748void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000749 fGraphicStateResources.unrefAll();
750 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000751 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000752 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000753 SkSafeUnref(fAnnotations);
epoger@google.comb58772f2013-03-08 09:09:10 +0000754 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000755
vandebo@chromium.org98594282011-07-25 22:34:12 +0000756 if (clearFontUsage) {
757 fFontGlyphUsage->reset();
758 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000759}
760
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000761void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000762 SkPaint newPaint = paint;
763 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000764 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000765 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000766}
767
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000768void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
769 ContentEntry* contentEntry) {
770 if (!contentEntry) {
771 return;
772 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000773 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
774 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000775 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000776 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000777 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000778 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000779 inverse.mapRect(&bbox);
780
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000781 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000782 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000783 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000784}
785
786void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
787 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000788 const SkPaint& passedPaint) {
789 if (count == 0) {
790 return;
791 }
792
epoger@google.comb58772f2013-03-08 09:09:10 +0000793 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
794 return;
795 }
796
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000797 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
798 // We only use this when there's a path effect because of the overhead
799 // of multiple calls to setUpContentEntry it causes.
800 if (passedPaint.getPathEffect()) {
801 if (d.fClip->isEmpty()) {
802 return;
803 }
804 SkDraw pointDraw(d);
805 pointDraw.fDevice = this;
806 pointDraw.drawPoints(mode, count, points, passedPaint, true);
807 return;
808 }
809
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000810 const SkPaint* paint = &passedPaint;
811 SkPaint modifiedPaint;
812
813 if (mode == SkCanvas::kPoints_PointMode &&
814 paint->getStrokeCap() != SkPaint::kRound_Cap) {
815 modifiedPaint = *paint;
816 paint = &modifiedPaint;
817 if (paint->getStrokeWidth()) {
818 // PDF won't draw a single point with square/butt caps because the
819 // orientation is ambiguous. Draw a rectangle instead.
820 modifiedPaint.setStyle(SkPaint::kFill_Style);
821 SkScalar strokeWidth = paint->getStrokeWidth();
822 SkScalar halfStroke = SkScalarHalf(strokeWidth);
823 for (size_t i = 0; i < count; i++) {
824 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
825 r.inset(-halfStroke, -halfStroke);
826 drawRect(d, r, modifiedPaint);
827 }
828 return;
829 } else {
830 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
831 }
832 }
833
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000834 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000835 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000836 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000837 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000838
839 switch (mode) {
840 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000841 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000842 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000843 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000844 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000845 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000846 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000847 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000848 break;
849 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000850 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000851 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000852 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000853 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000854 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000855 &content.entry()->fContent);
856 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000857 }
858 break;
859 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000860 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
861 for (size_t i = 0; i < count; i++) {
862 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000863 &content.entry()->fContent);
864 SkPDFUtils::ClosePath(&content.entry()->fContent);
865 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000866 }
867 break;
868 default:
869 SkASSERT(false);
870 }
871}
872
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000873void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000874 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000875 SkRect r = rect;
876 r.sort();
877
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000878 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000879 if (d.fClip->isEmpty()) {
880 return;
881 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000882 SkPath path;
883 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000884 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000885 return;
886 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000887
epoger@google.comb58772f2013-03-08 09:09:10 +0000888 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000889 return;
890 }
891
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000892 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000893 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000894 return;
895 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000896 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000897 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000898 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000899}
900
reed89443ab2014-06-27 11:34:19 -0700901void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000902 SkPath path;
903 path.addRRect(rrect);
904 this->drawPath(draw, path, paint, NULL, true);
905}
906
reed89443ab2014-06-27 11:34:19 -0700907void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
908 SkPath path;
909 path.addOval(oval);
910 this->drawPath(draw, path, paint, NULL, true);
911}
912
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000913void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000914 const SkPaint& paint, const SkMatrix* prePathMatrix,
915 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000916 SkPath modifiedPath;
917 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
918
919 SkMatrix matrix = *d.fMatrix;
920 if (prePathMatrix) {
921 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
922 if (!pathIsMutable) {
923 pathPtr = &modifiedPath;
924 pathIsMutable = true;
925 }
926 origPath.transform(*prePathMatrix, pathPtr);
927 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000928 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000929 }
930 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000931
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000932 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000933 if (d.fClip->isEmpty()) {
934 return;
935 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000936 if (!pathIsMutable) {
937 pathPtr = &modifiedPath;
938 pathIsMutable = true;
939 }
940 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000941
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000942 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000943 noEffectPaint.setPathEffect(NULL);
944 if (fill) {
945 noEffectPaint.setStyle(SkPaint::kFill_Style);
946 } else {
947 noEffectPaint.setStyle(SkPaint::kStroke_Style);
948 noEffectPaint.setStrokeWidth(0);
949 }
950 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000951 return;
952 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000953
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 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000957
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000958 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000959 return;
960 }
961
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000962 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000963 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000964 return;
965 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000966 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
967 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000968 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000969 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000970}
971
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000972void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
973 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000974 const SkPaint& paint,
975 SkCanvas::DrawBitmapRectFlags flags) {
976 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000977 SkMatrix matrix;
978 SkRect bitmapBounds, tmpSrc, tmpDst;
979 SkBitmap tmpBitmap;
980
981 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
982
983 // Compute matrix from the two rectangles
984 if (src) {
985 tmpSrc = *src;
986 } else {
987 tmpSrc = bitmapBounds;
988 }
989 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
990
991 const SkBitmap* bitmapPtr = &bitmap;
992
993 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
994 // needed (if the src was clipped). No check needed if src==null.
995 if (src) {
996 if (!bitmapBounds.contains(*src)) {
997 if (!tmpSrc.intersect(bitmapBounds)) {
998 return; // nothing to draw
999 }
1000 // recompute dst, based on the smaller tmpSrc
1001 matrix.mapRect(&tmpDst, tmpSrc);
1002 }
1003
1004 // since we may need to clamp to the borders of the src rect within
1005 // the bitmap, we extract a subset.
1006 // TODO: make sure this is handled in drawBitmap and remove from here.
1007 SkIRect srcIR;
1008 tmpSrc.roundOut(&srcIR);
1009 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1010 return;
1011 }
1012 bitmapPtr = &tmpBitmap;
1013
1014 // Since we did an extract, we need to adjust the matrix accordingly
1015 SkScalar dx = 0, dy = 0;
1016 if (srcIR.fLeft > 0) {
1017 dx = SkIntToScalar(srcIR.fLeft);
1018 }
1019 if (srcIR.fTop > 0) {
1020 dy = SkIntToScalar(srcIR.fTop);
1021 }
1022 if (dx || dy) {
1023 matrix.preTranslate(dx, dy);
1024 }
1025 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001026 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001027}
1028
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001029void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001030 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001031 if (d.fClip->isEmpty()) {
1032 return;
1033 }
1034
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001035 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001036 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001037 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1038 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001039}
1040
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001041void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001042 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001043 if (d.fClip->isEmpty()) {
1044 return;
1045 }
1046
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001047 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001048 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001049 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1050 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001051}
1052
halcanarybb264b72015-04-07 10:40:03 -07001053// Create a PDF string. Maximum length (in bytes) is 65,535.
1054// @param input A string value.
1055// @param len The length of the input array.
1056// @param wideChars True iff the upper byte in each uint16_t is
1057// significant and should be encoded and not
1058// discarded. If true, the upper byte is encoded
1059// first. Otherwise, we assert the upper byte is
1060// zero.
1061static SkString format_wide_string(const uint16_t* input,
1062 size_t len,
1063 bool wideChars) {
1064 if (wideChars) {
1065 SkASSERT(2 * len < 65535);
1066 static const char gHex[] = "0123456789ABCDEF";
1067 SkString result(4 * len + 2);
1068 result[0] = '<';
1069 for (size_t i = 0; i < len; i++) {
1070 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1071 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1072 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1073 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1074 }
1075 result[4 * len + 1] = '>';
1076 return result;
1077 } else {
1078 SkASSERT(len <= 65535);
1079 SkString tmp(len);
1080 for (size_t i = 0; i < len; i++) {
1081 SkASSERT(0 == input[i] >> 8);
1082 tmp[i] = static_cast<uint8_t>(input[i]);
1083 }
1084 return SkPDFString::FormatString(tmp.c_str(), tmp.size());
1085 }
1086}
1087
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001088void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001089 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001090 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1091 if (paint.getMaskFilter() != NULL) {
1092 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1093 // making text unreadable (e.g. same text twice when using CSS shadows).
1094 return;
1095 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001096 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001097 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001098 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001099 return;
1100 }
1101
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001102 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001103 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001104 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001105 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001106
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001107 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001108 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001109 content.entry()->fContent.writeText("BT\n");
1110 set_text_transform(x, y, textPaint.getTextSkewX(),
1111 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001112 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001113
1114 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1115
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001116 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001117 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1118 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001119
1120 int availableGlyphs = font->glyphsToPDFFontEncoding(
1121 glyphIDsCopy.begin() + consumedGlyphCount,
1122 numGlyphs - consumedGlyphCount);
1123 fFontGlyphUsage->noteGlyphUsage(
1124 font, glyphIDsCopy.begin() + consumedGlyphCount,
1125 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001126 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001127 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1128 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001129 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001130 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001131 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001132 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001133 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001134}
1135
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001136void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001137 const SkScalar pos[], int scalarsPerPos,
1138 const SkPoint& offset, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001139 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1140 if (paint.getMaskFilter() != NULL) {
1141 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1142 // making text unreadable (e.g. same text twice when using CSS shadows).
1143 return;
1144 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001145 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001146 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001147 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001148 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001149 return;
1150 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001151
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001152 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001153 const uint16_t* glyphIDs = NULL;
1154 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001155 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001156
1157 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001158 content.entry()->fContent.writeText("BT\n");
1159 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001160 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001161 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001162 uint16_t encodedValue = glyphIDs[i];
1163 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001164 // The current pdf font cannot encode the current glyph.
1165 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001166 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001167 font = content.entry()->fState.fFont;
1168 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1169 SkDEBUGFAIL("PDF could not encode glyph.");
1170 continue;
1171 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001172 }
bungeman22edc832014-10-03 07:55:58 -07001173
vandebo@chromium.org98594282011-07-25 22:34:12 +00001174 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001175 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1176 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1177
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001178 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001179 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001180 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001181 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001182 content.entry()->fContent.writeText(encodedString.c_str());
1183 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001184 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001185 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001186}
1187
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001188void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001189 int vertexCount, const SkPoint verts[],
1190 const SkPoint texs[], const SkColor colors[],
1191 SkXfermode* xmode, const uint16_t indices[],
1192 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001193 if (d.fClip->isEmpty()) {
1194 return;
1195 }
reed@google.com85e143c2013-12-30 15:51:25 +00001196 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001197}
1198
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001199void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1200 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001201 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001202 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001203 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001204 return;
1205 }
1206
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001207 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001208 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001209 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001210 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001211 return;
1212 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001213 if (content.needShape()) {
1214 SkPath shape;
1215 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001216 SkIntToScalar(device->width()),
1217 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001218 content.setShape(shape);
1219 }
1220 if (!content.needSource()) {
1221 return;
1222 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001223
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001224 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1225 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001226 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001227
1228 // Merge glyph sets from the drawn device.
1229 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001230}
1231
reed89443ab2014-06-27 11:34:19 -07001232SkImageInfo SkPDFDevice::imageInfo() const {
1233 return fLegacyBitmap.info();
1234}
1235
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001236void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1237 INHERITED::onAttachToCanvas(canvas);
1238
1239 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1240 fClipStack = canvas->getClipStack();
1241}
1242
1243void SkPDFDevice::onDetachFromCanvas() {
1244 INHERITED::onDetachFromCanvas();
1245
1246 fClipStack = NULL;
1247}
1248
reed4a8126e2014-09-22 07:29:03 -07001249SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1250 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001251}
1252
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001253ContentEntry* SkPDFDevice::getLastContentEntry() {
1254 if (fDrawingArea == kContent_DrawingArea) {
1255 return fLastContentEntry;
1256 } else {
1257 return fLastMarginContentEntry;
1258 }
1259}
1260
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001261SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001262 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001263 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001264 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001265 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001266 }
1267}
1268
1269void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1270 if (fDrawingArea == kContent_DrawingArea) {
1271 fLastContentEntry = contentEntry;
1272 } else {
1273 fLastMarginContentEntry = contentEntry;
1274 }
1275}
1276
1277void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001278 // A ScopedContentEntry only exists during the course of a draw call, so
1279 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001280 fDrawingArea = drawingArea;
1281}
1282
halcanary2b861552015-04-09 13:27:40 -07001283SkPDFDict* SkPDFDevice::createResourceDict() const {
1284 SkTDArray<SkPDFObject*> fonts;
1285 fonts.setReserve(fFontResources.count());
1286 for (SkPDFFont* font : fFontResources) {
1287 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001288 }
halcanary2b861552015-04-09 13:27:40 -07001289 return SkPDFResourceDict::Create(
1290 &fGraphicStateResources,
1291 &fShaderResources,
1292 &fXObjectResources,
1293 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001294}
1295
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001296const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1297 return fFontResources;
1298}
1299
reed@google.com2a006c12012-09-19 17:05:55 +00001300SkPDFArray* SkPDFDevice::copyMediaBox() const {
1301 // should this be a singleton?
1302 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001303
reed@google.com2a006c12012-09-19 17:05:55 +00001304 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001305 mediaBox->reserve(4);
1306 mediaBox->append(zero.get());
1307 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001308 mediaBox->appendInt(fPageSize.fWidth);
1309 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001310 return mediaBox;
1311}
1312
halcanary334fcbc2015-02-24 12:56:16 -08001313SkStreamAsset* SkPDFDevice::content() const {
1314 SkDynamicMemoryWStream buffer;
1315 this->writeContent(&buffer);
1316 return buffer.detachAsStream();
reed@google.com5667afc2011-06-27 14:42:15 +00001317}
1318
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001319void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1320 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001321 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1322 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001323 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001324 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001325 SkPoint translation;
1326 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001327 translation.negate();
1328 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1329 translation);
1330 gsState.updateMatrix(entry->fState.fMatrix);
1331 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001332
halcanary7af21502015-02-23 12:17:59 -08001333 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001334 entry = entry->fNext.get();
1335 }
1336 gsState.drainStack();
1337}
1338
halcanary334fcbc2015-02-24 12:56:16 -08001339void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001340 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001341 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001342 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001343
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001344 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1345 // colors the contentArea white before it starts drawing into it and
1346 // that currently acts as our clip.
1347 // Also, think about adding a transform here (or assume that the values
1348 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001349 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001350
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001351 // If the content area is the entire page, then we don't need to clip
1352 // the content area (PDF area clips to the page size). Otherwise,
1353 // we have to clip to the content area; we've already applied the
1354 // initial transform, so just clip to the device size.
1355 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001356 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1357 SkIntToScalar(this->height()));
halcanary334fcbc2015-02-24 12:56:16 -08001358 emit_clip(NULL, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001359 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001360
halcanary334fcbc2015-02-24 12:56:16 -08001361 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001362}
1363
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001364/* Draws an inverse filled path by using Path Ops to compute the positive
1365 * inverse using the current clip as the inverse bounds.
1366 * Return true if this was an inverse path and was properly handled,
1367 * otherwise returns false and the normal drawing routine should continue,
1368 * either as a (incorrect) fallback or because the path was not inverse
1369 * in the first place.
1370 */
1371bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001372 const SkPaint& paint, bool pathIsMutable,
1373 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001374 if (!origPath.isInverseFillType()) {
1375 return false;
1376 }
1377
1378 if (d.fClip->isEmpty()) {
1379 return false;
1380 }
1381
1382 SkPath modifiedPath;
1383 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1384 SkPaint noInversePaint(paint);
1385
1386 // Merge stroking operations into final path.
1387 if (SkPaint::kStroke_Style == paint.getStyle() ||
1388 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1389 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1390 if (doFillPath) {
1391 noInversePaint.setStyle(SkPaint::kFill_Style);
1392 noInversePaint.setStrokeWidth(0);
1393 pathPtr = &modifiedPath;
1394 } else {
1395 // To be consistent with the raster output, hairline strokes
1396 // are rendered as non-inverted.
1397 modifiedPath.toggleInverseFillType();
1398 drawPath(d, modifiedPath, paint, NULL, true);
1399 return true;
1400 }
1401 }
1402
1403 // Get bounds of clip in current transform space
1404 // (clip bounds are given in device space).
1405 SkRect bounds;
1406 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001407 SkMatrix totalMatrix = *d.fMatrix;
1408 if (prePathMatrix) {
1409 totalMatrix.preConcat(*prePathMatrix);
1410 }
1411 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001412 return false;
1413 }
1414 bounds.set(d.fClip->getBounds());
1415 transformInverse.mapRect(&bounds);
1416
1417 // Extend the bounds by the line width (plus some padding)
1418 // so the edge doesn't cause a visible stroke.
1419 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1420 paint.getStrokeWidth() + SK_Scalar1);
1421
1422 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1423 return false;
1424 }
1425
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001426 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001427 return true;
1428}
1429
epoger@google.comb58772f2013-03-08 09:09:10 +00001430bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1431 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001432 SkAnnotation* annotationInfo = p.getAnnotation();
1433 if (!annotationInfo) {
1434 return false;
1435 }
1436 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001437 if (urlData) {
1438 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001439 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001440 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001441 SkData* linkToName = annotationInfo->find(
1442 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001443 if (linkToName) {
1444 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001445 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001446 }
1447 return false;
1448}
1449
1450bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1451 const SkMatrix& matrix,
1452 const SkPaint& paint) {
1453 SkAnnotation* annotationInfo = paint.getAnnotation();
1454 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001455 return false;
1456 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001457 SkData* nameData = annotationInfo->find(
1458 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001459 if (nameData) {
1460 for (size_t i = 0; i < count; i++) {
1461 defineNamedDestination(nameData, points[i], matrix);
1462 }
reed@google.com44699382013-10-31 17:28:30 +00001463 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001464 }
1465 return false;
1466}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001467
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001468SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1469 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001470 SkMatrix transform = matrix;
1471 transform.postConcat(fInitialTransform);
1472 SkRect translatedRect;
1473 transform.mapRect(&translatedRect, r);
1474
reed@google.com2a006c12012-09-19 17:05:55 +00001475 if (NULL == fAnnotations) {
1476 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001477 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001478 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001479 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001480 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001481
epoger@google.comb58772f2013-03-08 09:09:10 +00001482 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001483 border->reserve(3);
1484 border->appendInt(0); // Horizontal corner radius.
1485 border->appendInt(0); // Vertical corner radius.
1486 border->appendInt(0); // Width, 0 = no border.
1487 annotation->insert("Border", border.get());
1488
epoger@google.comb58772f2013-03-08 09:09:10 +00001489 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001490 rect->reserve(4);
1491 rect->appendScalar(translatedRect.fLeft);
1492 rect->appendScalar(translatedRect.fTop);
1493 rect->appendScalar(translatedRect.fRight);
1494 rect->appendScalar(translatedRect.fBottom);
1495 annotation->insert("Rect", rect.get());
1496
epoger@google.comb58772f2013-03-08 09:09:10 +00001497 return annotation;
1498}
epoger@google.com1cad8982013-03-06 00:05:13 +00001499
epoger@google.comb58772f2013-03-08 09:09:10 +00001500void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1501 const SkMatrix& matrix) {
1502 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1503
1504 SkString url(static_cast<const char *>(urlData->data()),
1505 urlData->size() - 1);
1506 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1507 action->insertName("S", "URI");
1508 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1509 annotation->insert("A", action.get());
1510}
1511
1512void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1513 const SkMatrix& matrix) {
1514 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1515 SkString name(static_cast<const char *>(nameData->data()),
1516 nameData->size() - 1);
1517 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1518}
1519
1520struct NamedDestination {
1521 const SkData* nameData;
1522 SkPoint point;
1523
1524 NamedDestination(const SkData* nameData, const SkPoint& point)
1525 : nameData(nameData), point(point) {
1526 nameData->ref();
1527 }
1528
1529 ~NamedDestination() {
1530 nameData->unref();
1531 }
1532};
1533
1534void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1535 const SkMatrix& matrix) {
1536 SkMatrix transform = matrix;
1537 transform.postConcat(fInitialTransform);
1538 SkPoint translatedPoint;
1539 transform.mapXY(point.x(), point.y(), &translatedPoint);
1540 fNamedDestinations.push(
1541 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1542}
1543
halcanary6d622702015-03-25 08:45:42 -07001544void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
epoger@google.comb58772f2013-03-08 09:09:10 +00001545 int nDest = fNamedDestinations.count();
1546 for (int i = 0; i < nDest; i++) {
1547 NamedDestination* dest = fNamedDestinations[i];
1548 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1549 pdfDest->reserve(5);
1550 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1551 pdfDest->appendName("XYZ");
1552 pdfDest->appendScalar(dest->point.x());
1553 pdfDest->appendScalar(dest->point.y());
1554 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001555 dict->insert(static_cast<const char *>(dest->nameData->data()),
1556 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001557 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001558}
1559
reed@google.comfc641d02012-09-20 17:52:20 +00001560SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1561 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001562 // We always draw the form xobjects that we create back into the device, so
1563 // we simply preserve the font usage instead of pulling it out and merging
1564 // it back in later.
1565 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001566 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001567 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001568}
1569
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001570void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1571 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001572 const SkClipStack* clipStack,
1573 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001574 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001575 bool invertClip) {
1576 if (clipRegion.isEmpty() && !invertClip) {
1577 return;
1578 }
1579
halcanarybe27a112015-04-01 13:31:19 -07001580 SkAutoTUnref<SkPDFObject> sMaskGS(SkPDFGraphicState::GetSMaskGraphicState(
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001581 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1582
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001583 SkMatrix identity;
1584 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001585 SkPaint paint;
1586 paint.setXfermodeMode(mode);
1587 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001588 if (!content.entry()) {
1589 return;
1590 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001591 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001592 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001593 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001594
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001595 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001596 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001597 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001598}
1599
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001600ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1601 const SkRegion& clipRegion,
1602 const SkMatrix& matrix,
1603 const SkPaint& paint,
1604 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001605 SkPDFFormXObject** dst) {
1606 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001607 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001608 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001609 }
1610
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001611 // The clip stack can come from an SkDraw where it is technically optional.
1612 SkClipStack synthesizedClipStack;
1613 if (clipStack == NULL) {
1614 if (clipRegion == fExistingClipRegion) {
1615 clipStack = &fExistingClipStack;
1616 } else {
1617 // GraphicStackState::updateClip expects the clip stack to have
1618 // fExistingClip as a prefix, so start there, then set the clip
1619 // to the passed region.
1620 synthesizedClipStack = fExistingClipStack;
1621 SkPath clipPath;
1622 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001623 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1624 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001625 clipStack = &synthesizedClipStack;
1626 }
1627 }
1628
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001629 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1630 if (paint.getXfermode()) {
1631 paint.getXfermode()->asMode(&xfermode);
1632 }
1633
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001634 // For the following modes, we want to handle source and destination
1635 // separately, so make an object of what's already there.
1636 if (xfermode == SkXfermode::kClear_Mode ||
1637 xfermode == SkXfermode::kSrc_Mode ||
1638 xfermode == SkXfermode::kSrcIn_Mode ||
1639 xfermode == SkXfermode::kDstIn_Mode ||
1640 xfermode == SkXfermode::kSrcOut_Mode ||
1641 xfermode == SkXfermode::kDstOut_Mode ||
1642 xfermode == SkXfermode::kSrcATop_Mode ||
1643 xfermode == SkXfermode::kDstATop_Mode ||
1644 xfermode == SkXfermode::kModulate_Mode) {
1645 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001646 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001647 SkASSERT(isContentEmpty());
1648 } else if (xfermode != SkXfermode::kSrc_Mode &&
1649 xfermode != SkXfermode::kSrcOut_Mode) {
1650 // Except for Src and SrcOut, if there isn't anything already there,
1651 // then we're done.
1652 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001653 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001654 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001655 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001656 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001657
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001658 // Dst xfer mode doesn't draw source at all.
1659 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001660 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001661 }
1662
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001663 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001664 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001665
1666 ContentEntry* lastContentEntry = getLastContentEntry();
1667 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1668 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001669 } else {
1670 newEntry.reset(new ContentEntry);
1671 entry = newEntry.get();
1672 }
1673
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001674 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001675 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001676 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1677 entry->fState.compareInitialState(lastContentEntry->fState)) {
1678 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001679 }
1680
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001681 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001682 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001683 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001684 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001685 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001686 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001687 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001688 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001689 lastContentEntry->fNext.reset(entry);
1690 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001691 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001692 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001693 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001694}
1695
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001696void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001697 SkPDFFormXObject* dst,
1698 SkPath* shape) {
1699 if (xfermode != SkXfermode::kClear_Mode &&
1700 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001701 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001702 xfermode != SkXfermode::kSrcIn_Mode &&
1703 xfermode != SkXfermode::kDstIn_Mode &&
1704 xfermode != SkXfermode::kSrcOut_Mode &&
1705 xfermode != SkXfermode::kDstOut_Mode &&
1706 xfermode != SkXfermode::kSrcATop_Mode &&
1707 xfermode != SkXfermode::kDstATop_Mode &&
1708 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001709 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001710 return;
1711 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001712 if (xfermode == SkXfermode::kDstOver_Mode) {
1713 SkASSERT(!dst);
1714 ContentEntry* firstContentEntry = getContentEntries()->get();
1715 if (firstContentEntry->fContent.getOffset() == 0) {
1716 // For DstOver, an empty content entry was inserted before the rest
1717 // of the content entries. If nothing was drawn, it needs to be
1718 // removed.
1719 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1720 contentEntries->reset(firstContentEntry->fNext.detach());
1721 }
1722 return;
1723 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001724 if (!dst) {
1725 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1726 xfermode == SkXfermode::kSrcOut_Mode);
1727 return;
1728 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001729
1730 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001731 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001732 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001733 // Changing the current content into a form-xobject will destroy the clip
1734 // objects which is fine since the xobject will already be clipped. However
1735 // if source has shape, we need to clip it too, so a copy of the clip is
1736 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001737 SkClipStack clipStack = contentEntries->fState.fClipStack;
1738 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001739
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001740 SkMatrix identity;
1741 identity.reset();
1742 SkPaint stockPaint;
1743
reed@google.comfc641d02012-09-20 17:52:20 +00001744 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001745 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001746 // If nothing was drawn and there's no shape, then the draw was a
1747 // no-op, but dst needs to be restored for that to be true.
1748 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1749 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1750 // reduces to Dst.
1751 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1752 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001753 ScopedContentEntry content(this, &fExistingClipStack,
1754 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001755 stockPaint);
1756 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1757 &content.entry()->fContent);
1758 return;
1759 } else {
1760 xfermode = SkXfermode::kClear_Mode;
1761 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001762 } else {
1763 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001764 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001765 }
1766
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001767 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1768 // without alpha.
1769 if (xfermode == SkXfermode::kSrcATop_Mode) {
1770 // TODO(vandebo): In order to properly support SrcATop we have to track
1771 // the shape of what's been drawn at all times. It's the intersection of
1772 // the non-transparent parts of the device and the outlines (shape) of
1773 // all images and devices drawn.
1774 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001775 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001776 SkXfermode::kSrcOver_Mode, true);
1777 } else {
1778 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1779 SkPDFFormXObject* dstMask = srcFormXObject.get();
1780 if (shape != NULL) {
1781 // Draw shape into a form-xobject.
1782 SkDraw d;
1783 d.fMatrix = &identity;
1784 d.fClip = &clipRegion;
1785 d.fClipStack = &clipStack;
1786 SkPaint filledPaint;
1787 filledPaint.setColor(SK_ColorBLACK);
1788 filledPaint.setStyle(SkPaint::kFill_Style);
1789 this->drawPath(d, *shape, filledPaint, NULL, true);
1790
1791 dstMaskStorage.reset(createFormXObjectFromDevice());
1792 dstMask = dstMaskStorage.get();
1793 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001794 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1795 &fExistingClipStack, fExistingClipRegion,
1796 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001797 }
1798
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001799 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001800 return;
1801 } else if (xfermode == SkXfermode::kSrc_Mode ||
1802 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001803 ScopedContentEntry content(this, &fExistingClipStack,
1804 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001805 if (content.entry()) {
1806 SkPDFUtils::DrawFormXObject(
1807 this->addXObjectResource(srcFormXObject.get()),
1808 &content.entry()->fContent);
1809 }
1810 if (xfermode == SkXfermode::kSrc_Mode) {
1811 return;
1812 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001813 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001814 ScopedContentEntry content(this, &fExistingClipStack,
1815 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001816 if (content.entry()) {
1817 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1818 &content.entry()->fContent);
1819 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001820 }
1821
1822 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1823 xfermode == SkXfermode::kDstIn_Mode ||
1824 xfermode == SkXfermode::kSrcOut_Mode ||
1825 xfermode == SkXfermode::kDstOut_Mode ||
1826 xfermode == SkXfermode::kSrcATop_Mode ||
1827 xfermode == SkXfermode::kDstATop_Mode ||
1828 xfermode == SkXfermode::kModulate_Mode);
1829
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001830 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001831 xfermode == SkXfermode::kSrcOut_Mode ||
1832 xfermode == SkXfermode::kSrcATop_Mode) {
1833 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001834 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001835 SkXfermode::kSrcOver_Mode,
1836 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001837 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1839 if (xfermode == SkXfermode::kModulate_Mode) {
1840 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001841 dst, &fExistingClipStack,
1842 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001843 SkXfermode::kSrcOver_Mode, false);
1844 mode = SkXfermode::kMultiply_Mode;
1845 }
1846 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001847 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001848 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001849 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001850}
1851
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001852bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001853 ContentEntry* contentEntries = getContentEntries()->get();
1854 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1855 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001856 return true;
1857 }
1858 return false;
1859}
1860
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001861void SkPDFDevice::populateGraphicStateEntryFromPaint(
1862 const SkMatrix& matrix,
1863 const SkClipStack& clipStack,
1864 const SkRegion& clipRegion,
1865 const SkPaint& paint,
1866 bool hasText,
1867 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001868 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001869 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1870 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001871
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001872 entry->fMatrix = matrix;
1873 entry->fClipStack = clipStack;
1874 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001875 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1876 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001877
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001878 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001879 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001880 const SkShader* shader = paint.getShader();
1881 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001882 if (shader) {
1883 // PDF positions patterns relative to the initial transform, so
1884 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001885 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001886 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001887
1888 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001889 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001890 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001891
1892 // We need to apply the initial transform to bounds in order to get
1893 // bounds in a consistent coordinate system.
1894 SkRect boundsTemp;
1895 boundsTemp.set(bounds);
1896 fInitialTransform.mapRect(&boundsTemp);
1897 boundsTemp.roundOut(&bounds);
1898
halcanary792c80f2015-02-20 07:21:05 -08001899 SkScalar rasterScale =
1900 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
1901 pdfShader.reset(SkPDFShader::GetPDFShader(
1902 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001903
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001904 if (pdfShader.get()) {
1905 // pdfShader has been canonicalized so we can directly compare
1906 // pointers.
1907 int resourceIndex = fShaderResources.find(pdfShader.get());
1908 if (resourceIndex < 0) {
1909 resourceIndex = fShaderResources.count();
1910 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001911 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001912 }
1913 entry->fShaderIndex = resourceIndex;
1914 } else {
1915 // A color shader is treated as an invalid shader so we don't have
1916 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001917 SkShader::GradientInfo gradientInfo;
1918 SkColor gradientColor;
1919 gradientInfo.fColors = &gradientColor;
1920 gradientInfo.fColorOffsets = NULL;
1921 gradientInfo.fColorCount = 1;
1922 if (shader->asAGradient(&gradientInfo) ==
1923 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001924 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1925 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001926 }
1927 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001928 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001929
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001930 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001931 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001932 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001933 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001934 } else {
1935 SkPaint newPaint = paint;
1936 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001937 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001938 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001939 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001940 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001941 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001942
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001943 if (hasText) {
1944 entry->fTextScaleX = paint.getTextScaleX();
1945 entry->fTextFill = paint.getStyle();
1946 } else {
1947 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001948 }
1949}
1950
halcanarybe27a112015-04-01 13:31:19 -07001951int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001952 // Assumes that gs has been canonicalized (so we can directly compare
1953 // pointers).
1954 int result = fGraphicStateResources.find(gs);
1955 if (result < 0) {
1956 result = fGraphicStateResources.count();
1957 fGraphicStateResources.push(gs);
1958 gs->ref();
1959 }
1960 return result;
1961}
1962
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001963int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
1964 // Assumes that xobject has been canonicalized (so we can directly compare
1965 // pointers).
1966 int result = fXObjectResources.find(xObject);
1967 if (result < 0) {
1968 result = fXObjectResources.count();
1969 fXObjectResources.push(xObject);
1970 xObject->ref();
1971 }
1972 return result;
1973}
1974
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001975void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
1976 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001977 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001978 if (contentEntry->fState.fFont == NULL ||
1979 contentEntry->fState.fTextSize != paint.getTextSize() ||
1980 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001981 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001982 contentEntry->fContent.writeText("/");
1983 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
1984 SkPDFResourceDict::kFont_ResourceType,
1985 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001986 contentEntry->fContent.writeText(" ");
1987 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
1988 contentEntry->fContent.writeText(" Tf\n");
1989 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001990 }
1991}
1992
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001993int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary792c80f2015-02-20 07:21:05 -08001994 SkAutoTUnref<SkPDFFont> newFont(
1995 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001996 int resourceIndex = fFontResources.find(newFont.get());
1997 if (resourceIndex < 0) {
1998 resourceIndex = fFontResources.count();
1999 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002000 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002001 }
2002 return resourceIndex;
2003}
2004
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002005void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002006 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002007 const SkRegion& origClipRegion,
2008 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002009 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002010 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002011 SkMatrix matrix = origMatrix;
2012 SkRegion perspectiveBounds;
2013 const SkRegion* clipRegion = &origClipRegion;
2014 SkBitmap perspectiveBitmap;
2015 const SkBitmap* bitmap = &origBitmap;
2016 SkBitmap tmpSubsetBitmap;
2017
2018 // Rasterize the bitmap using perspective in a new bitmap.
2019 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002020 if (fRasterDpi == 0) {
2021 return;
2022 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002023 SkBitmap* subsetBitmap;
2024 if (srcRect) {
2025 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2026 return;
2027 }
2028 subsetBitmap = &tmpSubsetBitmap;
2029 } else {
2030 subsetBitmap = &tmpSubsetBitmap;
2031 *subsetBitmap = origBitmap;
2032 }
2033 srcRect = NULL;
2034
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002035 // Transform the bitmap in the new space, without taking into
2036 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002037 SkPath perspectiveOutline;
2038 perspectiveOutline.addRect(
2039 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2040 SkIntToScalar(subsetBitmap->height())));
2041 perspectiveOutline.transform(origMatrix);
2042
2043 // TODO(edisonn): perf - use current clip too.
2044 // Retrieve the bounds of the new shape.
2045 SkRect bounds = perspectiveOutline.getBounds();
2046
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002047 // Transform the bitmap in the new space, taking into
2048 // account the initial transform.
2049 SkMatrix total = origMatrix;
2050 total.postConcat(fInitialTransform);
2051 total.postScale(SkIntToScalar(fRasterDpi) /
2052 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2053 SkIntToScalar(fRasterDpi) /
2054 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2055 SkPath physicalPerspectiveOutline;
2056 physicalPerspectiveOutline.addRect(
2057 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2058 SkIntToScalar(subsetBitmap->height())));
2059 physicalPerspectiveOutline.transform(total);
2060
2061 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2062 bounds.width();
2063 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2064 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002065
2066 // TODO(edisonn): A better approach would be to use a bitmap shader
2067 // (in clamp mode) and draw a rect over the entire bounding box. Then
2068 // intersect perspectiveOutline to the clip. That will avoid introducing
2069 // alpha to the image while still giving good behavior at the edge of
2070 // the image. Avoiding alpha will reduce the pdf size and generation
2071 // CPU time some.
2072
reed@google.com9ebcac52014-01-24 18:53:42 +00002073 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2074 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002075 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002076 return;
2077 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002078 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2079
reed89443ab2014-06-27 11:34:19 -07002080 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002081
2082 SkScalar deltaX = bounds.left();
2083 SkScalar deltaY = bounds.top();
2084
2085 SkMatrix offsetMatrix = origMatrix;
2086 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002087 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002088
2089 // Translate the draw in the new canvas, so we perfectly fit the
2090 // shape in the bitmap.
2091 canvas.setMatrix(offsetMatrix);
2092
2093 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2094
2095 // Make sure the final bits are in the bitmap.
2096 canvas.flush();
2097
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002098 // In the new space, we use the identity matrix translated
2099 // and scaled to reflect DPI.
2100 matrix.setScale(1 / scaleX, 1 / scaleY);
2101 matrix.postTranslate(deltaX, deltaY);
2102
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002103 perspectiveBounds.setRect(
2104 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2105 SkScalarFloorToInt(bounds.y()),
2106 SkScalarCeilToInt(bounds.width()),
2107 SkScalarCeilToInt(bounds.height())));
2108 clipRegion = &perspectiveBounds;
2109 srcRect = NULL;
2110 bitmap = &perspectiveBitmap;
2111 }
2112
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002113 SkMatrix scaled;
2114 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002115 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2116 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002117 // Scale the image up from 1x1 to WxH.
halcanaryf622a6c2014-10-24 12:54:53 -07002118 SkIRect subset = bitmap->bounds();
reed@google.coma6d59f62011-03-07 21:29:21 +00002119 scaled.postScale(SkIntToScalar(subset.width()),
2120 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002121 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002122 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002123 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2124 return;
2125 }
2126 if (content.needShape()) {
2127 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002128 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
halcanarydb0dcc72015-03-20 12:31:52 -07002129 SkIntToScalar(subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002130 shape.transform(matrix);
2131 content.setShape(shape);
2132 }
2133 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002134 return;
2135 }
2136
halcanarydb0dcc72015-03-20 12:31:52 -07002137 SkBitmap subsetBitmap;
2138 // Should extractSubset be done by the SkPDFDevice?
2139 if (!bitmap->extractSubset(&subsetBitmap, subset)) {
2140 return;
2141 }
2142 SkAutoTUnref<SkPDFObject> image(SkPDFBitmap::Create(fCanon, subsetBitmap));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002143 if (!image) {
2144 return;
2145 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002146
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002147 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002148 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002149}