blob: 3b0d6f72ae5a1fdeaf51e41f7e2c536486c61084 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000015#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000016#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000017#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000018#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070019#include "SkPDFBitmap.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000023#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000024#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000025#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000026#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000027#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000028#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000029#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000030#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070031#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000032#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000033#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000034#include "SkTypefacePriv.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000035
edisonn@google.com73a7ea32013-11-11 20:55:15 +000036#define DPI_FOR_RASTER_SCALE_ONE 72
37
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000038// Utility functions
39
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000040static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000041 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
reed80ea19c2015-05-12 10:37:34 -070042 SkScalar colorScale = SkScalarInvert(0xFF);
43 SkPDFUtils::AppendScalar(SkColorGetR(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000044 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070045 SkPDFUtils::AppendScalar(SkColorGetG(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000046 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070047 SkPDFUtils::AppendScalar(SkColorGetB(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000048 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000049}
50
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000051static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000052 SkPaint result = paint;
53 if (result.isFakeBoldText()) {
54 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
55 kStdFakeBoldInterpKeys,
56 kStdFakeBoldInterpValues,
57 kStdFakeBoldInterpLength);
58 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000059 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000060 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000061 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000062 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000063 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000064 result.setStrokeWidth(width);
65 }
66 return result;
67}
68
69// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000070static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000071 const uint16_t* glyphs, size_t len,
72 SkScalar* x, SkScalar* y) {
73 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000074 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000075 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000076
77 SkMatrix ident;
78 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000079 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080 SkGlyphCache* cache = autoCache.getCache();
81
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000082 const char* start = reinterpret_cast<const char*>(glyphs);
83 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000084 SkFixed xAdv = 0, yAdv = 0;
85
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000086 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000087 while (start < stop) {
88 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
89 xAdv += glyph.fAdvanceX;
90 yAdv += glyph.fAdvanceY;
91 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000092 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000093 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000094 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000095
96 SkScalar xAdj = SkFixedToScalar(xAdv);
97 SkScalar yAdj = SkFixedToScalar(yAdv);
98 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
99 xAdj = SkScalarHalf(xAdj);
100 yAdj = SkScalarHalf(yAdj);
101 }
102 *x = *x - xAdj;
103 *y = *y - yAdj;
104}
105
robertphillips@google.coma4662862013-11-21 14:24:16 +0000106static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000107 SkAutoResolveDefaultTypeface autoResolve(typeface);
108 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000109 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000110}
111
112typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
113
reed@google.comaec40662014-04-18 19:29:07 +0000114static int force_glyph_encoding(const SkPaint& paint, const void* text,
115 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700116 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000117 // Make sure we have a glyph id encoding.
118 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
reed@google.comaec40662014-04-18 19:29:07 +0000119 int numGlyphs = paint.textToGlyphs(text, len, NULL);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000120 storage->reset(numGlyphs);
121 paint.textToGlyphs(text, len, storage->get());
122 *glyphIDs = storage->get();
123 return numGlyphs;
124 }
125
126 // For user supplied glyph ids we need to validate them.
127 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000128 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700129 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000130
131 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000132 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000133 for (validated = 0; validated < numGlyphs; ++validated) {
134 if (input[validated] > maxGlyphID) {
135 break;
136 }
137 }
138 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700139 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000140 return numGlyphs;
141 }
142
143 // Silently drop anything out of range.
144 storage->reset(numGlyphs);
145 if (validated > 0) {
146 memcpy(storage->get(), input, validated * sizeof(uint16_t));
147 }
148
reed@google.comaec40662014-04-18 19:29:07 +0000149 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000150 storage->get()[i] = input[i];
151 if (input[i] > maxGlyphID) {
152 storage->get()[i] = 0;
153 }
154 }
155 *glyphIDs = storage->get();
156 return numGlyphs;
157}
158
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000159static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
160 SkWStream* content) {
161 // Flip the text about the x-axis to account for origin swap and include
162 // the passed parameters.
163 content->writeText("1 0 ");
halcanarybc4696b2015-05-06 10:56:04 -0700164 SkPDFUtils::AppendScalar(0 - textSkewX, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000165 content->writeText(" -1 ");
halcanarybc4696b2015-05-06 10:56:04 -0700166 SkPDFUtils::AppendScalar(x, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000167 content->writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -0700168 SkPDFUtils::AppendScalar(y, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000169 content->writeText(" Tm\n");
170}
171
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000172// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
173// later being our representation of an object in the PDF file.
174struct GraphicStateEntry {
175 GraphicStateEntry();
176
177 // Compare the fields we care about when setting up a new content entry.
178 bool compareInitialState(const GraphicStateEntry& b);
179
180 SkMatrix fMatrix;
181 // We can't do set operations on Paths, though PDF natively supports
182 // intersect. If the clip stack does anything other than intersect,
183 // we have to fall back to the region. Treat fClipStack as authoritative.
184 // See http://code.google.com/p/skia/issues/detail?id=221
185 SkClipStack fClipStack;
186 SkRegion fClipRegion;
187
188 // When emitting the content entry, we will ensure the graphic state
189 // is set to these values first.
190 SkColor fColor;
191 SkScalar fTextScaleX; // Zero means we don't care what the value is.
192 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
193 int fShaderIndex;
194 int fGraphicStateIndex;
195
196 // We may change the font (i.e. for Type1 support) within a
197 // ContentEntry. This is the one currently in effect, or NULL if none.
198 SkPDFFont* fFont;
199 // In PDF, text size has no default value. It is only valid if fFont is
200 // not NULL.
201 SkScalar fTextSize;
202};
203
204GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
205 fTextScaleX(SK_Scalar1),
206 fTextFill(SkPaint::kFill_Style),
207 fShaderIndex(-1),
208 fGraphicStateIndex(-1),
209 fFont(NULL),
210 fTextSize(SK_ScalarNaN) {
211 fMatrix.reset();
212}
213
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000214bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
215 return fColor == cur.fColor &&
216 fShaderIndex == cur.fShaderIndex &&
217 fGraphicStateIndex == cur.fGraphicStateIndex &&
218 fMatrix == cur.fMatrix &&
219 fClipStack == cur.fClipStack &&
220 (fTextScaleX == 0 ||
221 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000222}
223
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000224class GraphicStackState {
225public:
226 GraphicStackState(const SkClipStack& existingClipStack,
227 const SkRegion& existingClipRegion,
228 SkWStream* contentStream)
229 : fStackDepth(0),
230 fContentStream(contentStream) {
231 fEntries[0].fClipStack = existingClipStack;
232 fEntries[0].fClipRegion = existingClipRegion;
233 }
234
235 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000236 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000237 void updateMatrix(const SkMatrix& matrix);
238 void updateDrawingState(const GraphicStateEntry& state);
239
240 void drainStack();
241
242private:
243 void push();
244 void pop();
245 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
246
247 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
248 static const int kMaxStackDepth = 12;
249 GraphicStateEntry fEntries[kMaxStackDepth + 1];
250 int fStackDepth;
251 SkWStream* fContentStream;
252};
253
254void GraphicStackState::drainStack() {
255 while (fStackDepth) {
256 pop();
257 }
258}
259
260void GraphicStackState::push() {
261 SkASSERT(fStackDepth < kMaxStackDepth);
262 fContentStream->writeText("q\n");
263 fStackDepth++;
264 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
265}
266
267void GraphicStackState::pop() {
268 SkASSERT(fStackDepth > 0);
269 fContentStream->writeText("Q\n");
270 fStackDepth--;
271}
272
robertphillips@google.com80214e22012-07-20 15:33:18 +0000273// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000274// and then skips over the leading entries as specified in prefix. It requires
275// and asserts that "prefix" will be a prefix to "stack."
276static void skip_clip_stack_prefix(const SkClipStack& prefix,
277 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000278 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000279 SkClipStack::B2TIter prefixIter(prefix);
280 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000281
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000282 const SkClipStack::Element* prefixEntry;
283 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000284
285 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000286 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000287 iterEntry = iter->next();
288 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000289 // Because of SkClipStack does internal intersection, the last clip
290 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000291 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000292 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
293 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
294 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000295 // back up the iterator by one
296 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000297 prefixEntry = prefixIter.next();
298 break;
299 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000300 }
301
302 SkASSERT(prefixEntry == NULL);
303}
304
305static void emit_clip(SkPath* clipPath, SkRect* clipRect,
306 SkWStream* contentStream) {
307 SkASSERT(clipPath || clipRect);
308
309 SkPath::FillType clipFill;
310 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000311 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000312 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000313 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000314 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
315 clipFill = SkPath::kWinding_FillType;
316 }
317
318 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
319 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
320 if (clipFill == SkPath::kEvenOdd_FillType) {
321 contentStream->writeText("W* n\n");
322 } else {
323 contentStream->writeText("W n\n");
324 }
325}
326
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000327/* Calculate an inverted path's equivalent non-inverted path, given the
328 * canvas bounds.
329 * outPath may alias with invPath (since this is supported by PathOps).
330 */
331static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
332 SkPath* outPath) {
333 SkASSERT(invPath.isInverseFillType());
334
335 SkPath clipPath;
336 clipPath.addRect(bounds);
337
338 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
339}
340
fmalita632e92f2015-04-22 15:02:03 -0700341#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000342// Sanity check the numerical values of the SkRegion ops and PathOps ops
343// enums so region_op_to_pathops_op can do a straight passthrough cast.
344// If these are failing, it may be necessary to make region_op_to_pathops_op
345// do more.
346SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
347 region_pathop_mismatch);
348SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
349 region_pathop_mismatch);
350SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
351 region_pathop_mismatch);
352SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
353 region_pathop_mismatch);
354SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
355 (int)kReverseDifference_PathOp,
356 region_pathop_mismatch);
357
358static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
359 SkASSERT(op >= 0);
360 SkASSERT(op <= SkRegion::kReverseDifference_Op);
361 return (SkPathOp)op;
362}
363
364/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
365 * Returns true if successful, or false if not successful.
366 * If successful, the resulting clip is stored in outClipPath.
367 * If not successful, outClipPath is undefined, and a fallback method
368 * should be used.
369 */
370static bool get_clip_stack_path(const SkMatrix& transform,
371 const SkClipStack& clipStack,
372 const SkRegion& clipRegion,
373 SkPath* outClipPath) {
374 outClipPath->reset();
375 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
376
377 const SkClipStack::Element* clipEntry;
378 SkClipStack::Iter iter;
379 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
380 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
381 SkPath entryPath;
382 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
383 outClipPath->reset();
384 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
385 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000386 } else {
387 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000388 }
389 entryPath.transform(transform);
390
391 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
392 *outClipPath = entryPath;
393 } else {
394 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
395 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
396 return false;
397 }
398 }
399 }
400
401 if (outClipPath->isInverseFillType()) {
402 // The bounds are slightly outset to ensure this is correct in the
403 // face of floating-point accuracy and possible SkRegion bitmap
404 // approximations.
405 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
406 clipBounds.outset(SK_Scalar1, SK_Scalar1);
407 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
408 return false;
409 }
410 }
411 return true;
412}
413#endif
414
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000415// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000416// graphic state stack, and the fact that we can know all the clips used
417// on the page to optimize this.
418void GraphicStackState::updateClip(const SkClipStack& clipStack,
419 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000420 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000421 if (clipStack == currentEntry()->fClipStack) {
422 return;
423 }
424
425 while (fStackDepth > 0) {
426 pop();
427 if (clipStack == currentEntry()->fClipStack) {
428 return;
429 }
430 }
431 push();
432
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000433 currentEntry()->fClipStack = clipStack;
434 currentEntry()->fClipRegion = clipRegion;
435
436 SkMatrix transform;
437 transform.setTranslate(translation.fX, translation.fY);
438
fmalita632e92f2015-04-22 15:02:03 -0700439#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000440 SkPath clipPath;
441 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
442 emit_clip(&clipPath, NULL, fContentStream);
443 return;
444 }
445#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000446 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
447 // already been applied. (If this is a top level device, then it specifies
448 // a clip to the content area. If this is a layer, then it specifies
449 // the clip in effect when the layer was created.) There's no need to
450 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
451 // initial clip on the parent layer. (This means there's a bug if the user
452 // expands the clip and then uses any xfer mode that uses dst:
453 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000454 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000455 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
456
457 // If the clip stack does anything other than intersect or if it uses
458 // an inverse fill type, we have to fall back to the clip region.
459 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000460 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000461 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000462 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
463 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000464 needRegion = true;
465 break;
466 }
467 }
468
469 if (needRegion) {
470 SkPath clipPath;
471 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
472 emit_clip(&clipPath, NULL, fContentStream);
473 } else {
474 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000475 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000476 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000477 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
478 switch (clipEntry->getType()) {
479 case SkClipStack::Element::kRect_Type: {
480 SkRect translatedClip;
481 transform.mapRect(&translatedClip, clipEntry->getRect());
482 emit_clip(NULL, &translatedClip, fContentStream);
483 break;
484 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000485 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000486 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000487 clipEntry->asPath(&translatedPath);
488 translatedPath.transform(transform, &translatedPath);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000489 emit_clip(&translatedPath, NULL, fContentStream);
490 break;
491 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000492 }
493 }
494 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000495}
496
497void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
498 if (matrix == currentEntry()->fMatrix) {
499 return;
500 }
501
502 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
503 SkASSERT(fStackDepth > 0);
504 SkASSERT(fEntries[fStackDepth].fClipStack ==
505 fEntries[fStackDepth -1].fClipStack);
506 pop();
507
508 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
509 }
510 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
511 return;
512 }
513
514 push();
515 SkPDFUtils::AppendTransform(matrix, fContentStream);
516 currentEntry()->fMatrix = matrix;
517}
518
519void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
520 // PDF treats a shader as a color, so we only set one or the other.
521 if (state.fShaderIndex >= 0) {
522 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000523 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000524 currentEntry()->fShaderIndex = state.fShaderIndex;
525 }
526 } else {
527 if (state.fColor != currentEntry()->fColor ||
528 currentEntry()->fShaderIndex >= 0) {
529 emit_pdf_color(state.fColor, fContentStream);
530 fContentStream->writeText("RG ");
531 emit_pdf_color(state.fColor, fContentStream);
532 fContentStream->writeText("rg\n");
533 currentEntry()->fColor = state.fColor;
534 currentEntry()->fShaderIndex = -1;
535 }
536 }
537
538 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000539 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000540 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
541 }
542
543 if (state.fTextScaleX) {
544 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
545 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
546 SkIntToScalar(100));
halcanarybc4696b2015-05-06 10:56:04 -0700547 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000548 fContentStream->writeText(" Tz\n");
549 currentEntry()->fTextScaleX = state.fTextScaleX;
550 }
551 if (state.fTextFill != currentEntry()->fTextFill) {
552 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
553 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
554 enum_must_match_value);
555 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
556 enum_must_match_value);
557 fContentStream->writeDecAsText(state.fTextFill);
558 fContentStream->writeText(" Tr\n");
559 currentEntry()->fTextFill = state.fTextFill;
560 }
561 }
562}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000563
reed76033be2015-03-14 10:54:31 -0700564static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700565 // PDF does not support image filters, so render them on CPU.
566 // Note that this rendering is done at "screen" resolution (100dpi), not
567 // printer resolution.
568 // FIXME: It may be possible to express some filters natively using PDF
569 // to improve quality and file size (http://skbug.com/3043)
reed76033be2015-03-14 10:54:31 -0700570
571 // TODO: should we return true if there is a colorfilter?
572 return layerPaint.getImageFilter() != NULL;
573}
574
575SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
halcanary00b7e5e2015-04-15 13:05:18 -0700576 if (cinfo.fForImageFilter ||
577 (layerPaint && not_supported_for_layers(*layerPaint))) {
reed61f501f2015-04-29 08:34:00 -0700578 return NULL;
senorblancob0e89dc2014-10-20 14:03:12 -0700579 }
fmalita6987dca2014-11-13 08:33:37 -0800580 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanarya1f1ee92015-02-20 06:17:26 -0800581 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000582}
583
584
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000585struct ContentEntry {
586 GraphicStateEntry fState;
587 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000588 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000589
590 // If the stack is too deep we could get Stack Overflow.
591 // So we manually destruct the object.
592 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000593 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000594 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000595 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000596 // When the destructor is called, fNext is NULL and exits.
597 delete val;
598 val = valNext;
599 }
600 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000601};
602
603// A helper class to automatically finish a ContentEntry at the end of a
604// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000605class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000606public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000607 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
608 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000609 : fDevice(device),
610 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000611 fXfermode(SkXfermode::kSrcOver_Mode),
612 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000613 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
614 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000615 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
616 const SkRegion& clipRegion, const SkMatrix& matrix,
617 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618 : fDevice(device),
619 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000620 fXfermode(SkXfermode::kSrcOver_Mode),
621 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000622 init(clipStack, clipRegion, matrix, paint, hasText);
623 }
624
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000625 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000626 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000627 SkPath* shape = &fShape;
628 if (shape->isEmpty()) {
629 shape = NULL;
630 }
631 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 }
reed@google.comfc641d02012-09-20 17:52:20 +0000633 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000634 }
635
636 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000637
638 /* Returns true when we explicitly need the shape of the drawing. */
639 bool needShape() {
640 switch (fXfermode) {
641 case SkXfermode::kClear_Mode:
642 case SkXfermode::kSrc_Mode:
643 case SkXfermode::kSrcIn_Mode:
644 case SkXfermode::kSrcOut_Mode:
645 case SkXfermode::kDstIn_Mode:
646 case SkXfermode::kDstOut_Mode:
647 case SkXfermode::kSrcATop_Mode:
648 case SkXfermode::kDstATop_Mode:
649 case SkXfermode::kModulate_Mode:
650 return true;
651 default:
652 return false;
653 }
654 }
655
656 /* Returns true unless we only need the shape of the drawing. */
657 bool needSource() {
658 if (fXfermode == SkXfermode::kClear_Mode) {
659 return false;
660 }
661 return true;
662 }
663
664 /* If the shape is different than the alpha component of the content, then
665 * setShape should be called with the shape. In particular, images and
666 * devices have rectangular shape.
667 */
668 void setShape(const SkPath& shape) {
669 fShape = shape;
670 }
671
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000672private:
673 SkPDFDevice* fDevice;
674 ContentEntry* fContentEntry;
675 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000676 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000677 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000678
679 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
680 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000681 // Shape has to be flatten before we get here.
682 if (matrix.hasPerspective()) {
683 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000684 return;
685 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000686 if (paint.getXfermode()) {
687 paint.getXfermode()->asMode(&fXfermode);
688 }
689 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
690 matrix, paint, hasText,
691 &fDstFormXObject);
692 }
693};
694
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000695////////////////////////////////////////////////////////////////////////////////
696
halcanarya1f1ee92015-02-20 06:17:26 -0800697SkPDFDevice::SkPDFDevice(SkISize pageSize,
698 SkScalar rasterDpi,
699 SkPDFCanon* canon,
700 bool flip)
reed89443ab2014-06-27 11:34:19 -0700701 : fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800702 , fContentSize(pageSize)
703 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
704 , fAnnotations(NULL)
reed89443ab2014-06-27 11:34:19 -0700705 , fLastContentEntry(NULL)
706 , fLastMarginContentEntry(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800707 , fDrawingArea(kContent_DrawingArea)
reed89443ab2014-06-27 11:34:19 -0700708 , fClipStack(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800709 , fFontGlyphUsage(SkNEW(SkPDFGlyphSetMap))
710 , fRasterDpi(rasterDpi)
711 , fCanon(canon) {
712 SkASSERT(pageSize.width() > 0);
713 SkASSERT(pageSize.height() > 0);
714 fLegacyBitmap.setInfo(
715 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
716 if (flip) {
717 // Skia generally uses the top left as the origin but PDF
718 // natively has the origin at the bottom left. This matrix
719 // corrects for that. But that only needs to be done once, we
720 // don't do it when layering.
721 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
722 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
723 } else {
724 fInitialTransform.setIdentity();
725 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000726}
727
728SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000729 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000730}
731
732void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000733 fAnnotations = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000734 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000735 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000736 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000737 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000738 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000739 if (fFontGlyphUsage.get() == NULL) {
halcanary792c80f2015-02-20 07:21:05 -0800740 fFontGlyphUsage.reset(SkNEW(SkPDFGlyphSetMap));
vandebo@chromium.org98594282011-07-25 22:34:12 +0000741 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000742}
743
vandebo@chromium.org98594282011-07-25 22:34:12 +0000744void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000745 fGraphicStateResources.unrefAll();
746 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000747 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000748 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000749 SkSafeUnref(fAnnotations);
epoger@google.comb58772f2013-03-08 09:09:10 +0000750 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000751
vandebo@chromium.org98594282011-07-25 22:34:12 +0000752 if (clearFontUsage) {
753 fFontGlyphUsage->reset();
754 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000755}
756
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000757void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000758 SkPaint newPaint = paint;
759 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000760 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000761 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000762}
763
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000764void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
765 ContentEntry* contentEntry) {
766 if (!contentEntry) {
767 return;
768 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000769 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
770 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000771 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000772 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000773 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000774 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000775 inverse.mapRect(&bbox);
776
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000777 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000778 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000779 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000780}
781
782void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
783 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000784 const SkPaint& passedPaint) {
785 if (count == 0) {
786 return;
787 }
788
epoger@google.comb58772f2013-03-08 09:09:10 +0000789 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
790 return;
791 }
792
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000793 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
794 // We only use this when there's a path effect because of the overhead
795 // of multiple calls to setUpContentEntry it causes.
796 if (passedPaint.getPathEffect()) {
797 if (d.fClip->isEmpty()) {
798 return;
799 }
800 SkDraw pointDraw(d);
801 pointDraw.fDevice = this;
802 pointDraw.drawPoints(mode, count, points, passedPaint, true);
803 return;
804 }
805
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000806 const SkPaint* paint = &passedPaint;
807 SkPaint modifiedPaint;
808
809 if (mode == SkCanvas::kPoints_PointMode &&
810 paint->getStrokeCap() != SkPaint::kRound_Cap) {
811 modifiedPaint = *paint;
812 paint = &modifiedPaint;
813 if (paint->getStrokeWidth()) {
814 // PDF won't draw a single point with square/butt caps because the
815 // orientation is ambiguous. Draw a rectangle instead.
816 modifiedPaint.setStyle(SkPaint::kFill_Style);
817 SkScalar strokeWidth = paint->getStrokeWidth();
818 SkScalar halfStroke = SkScalarHalf(strokeWidth);
819 for (size_t i = 0; i < count; i++) {
820 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
821 r.inset(-halfStroke, -halfStroke);
822 drawRect(d, r, modifiedPaint);
823 }
824 return;
825 } else {
826 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
827 }
828 }
829
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000830 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000831 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000832 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000833 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000834
835 switch (mode) {
836 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000837 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000838 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000839 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000840 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000841 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000842 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000843 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000844 break;
845 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000846 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000847 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000848 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000849 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000850 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000851 &content.entry()->fContent);
852 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000853 }
854 break;
855 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000856 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
857 for (size_t i = 0; i < count; i++) {
858 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000859 &content.entry()->fContent);
860 SkPDFUtils::ClosePath(&content.entry()->fContent);
861 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000862 }
863 break;
864 default:
865 SkASSERT(false);
866 }
867}
868
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000869void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000870 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000871 SkRect r = rect;
872 r.sort();
873
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000874 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000875 if (d.fClip->isEmpty()) {
876 return;
877 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000878 SkPath path;
879 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000880 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000881 return;
882 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000883
epoger@google.comb58772f2013-03-08 09:09:10 +0000884 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000885 return;
886 }
887
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000888 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000889 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000890 return;
891 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000892 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000893 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000894 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000895}
896
reed89443ab2014-06-27 11:34:19 -0700897void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000898 SkPath path;
899 path.addRRect(rrect);
900 this->drawPath(draw, path, paint, NULL, true);
901}
902
reed89443ab2014-06-27 11:34:19 -0700903void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
904 SkPath path;
905 path.addOval(oval);
906 this->drawPath(draw, path, paint, NULL, true);
907}
908
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000909void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000910 const SkPaint& paint, const SkMatrix* prePathMatrix,
911 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000912 SkPath modifiedPath;
913 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
914
915 SkMatrix matrix = *d.fMatrix;
916 if (prePathMatrix) {
917 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
918 if (!pathIsMutable) {
919 pathPtr = &modifiedPath;
920 pathIsMutable = true;
921 }
922 origPath.transform(*prePathMatrix, pathPtr);
923 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000924 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000925 }
926 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000927
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000928 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000929 if (d.fClip->isEmpty()) {
930 return;
931 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000932 if (!pathIsMutable) {
933 pathPtr = &modifiedPath;
934 pathIsMutable = true;
935 }
936 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000937
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000938 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000939 noEffectPaint.setPathEffect(NULL);
940 if (fill) {
941 noEffectPaint.setStyle(SkPaint::kFill_Style);
942 } else {
943 noEffectPaint.setStyle(SkPaint::kStroke_Style);
944 noEffectPaint.setStrokeWidth(0);
945 }
946 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000947 return;
948 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000949
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000950 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000951 return;
952 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000953
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000954 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000955 return;
956 }
957
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000958 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000959 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000960 return;
961 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000962 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
963 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000964 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000965 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000966}
967
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000968void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
969 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000970 const SkPaint& paint,
971 SkCanvas::DrawBitmapRectFlags flags) {
972 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000973 SkMatrix matrix;
974 SkRect bitmapBounds, tmpSrc, tmpDst;
975 SkBitmap tmpBitmap;
976
977 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
978
979 // Compute matrix from the two rectangles
980 if (src) {
981 tmpSrc = *src;
982 } else {
983 tmpSrc = bitmapBounds;
984 }
985 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
986
987 const SkBitmap* bitmapPtr = &bitmap;
988
989 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
990 // needed (if the src was clipped). No check needed if src==null.
991 if (src) {
992 if (!bitmapBounds.contains(*src)) {
993 if (!tmpSrc.intersect(bitmapBounds)) {
994 return; // nothing to draw
995 }
996 // recompute dst, based on the smaller tmpSrc
997 matrix.mapRect(&tmpDst, tmpSrc);
998 }
999
1000 // since we may need to clamp to the borders of the src rect within
1001 // the bitmap, we extract a subset.
1002 // TODO: make sure this is handled in drawBitmap and remove from here.
1003 SkIRect srcIR;
1004 tmpSrc.roundOut(&srcIR);
1005 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1006 return;
1007 }
1008 bitmapPtr = &tmpBitmap;
1009
1010 // Since we did an extract, we need to adjust the matrix accordingly
1011 SkScalar dx = 0, dy = 0;
1012 if (srcIR.fLeft > 0) {
1013 dx = SkIntToScalar(srcIR.fLeft);
1014 }
1015 if (srcIR.fTop > 0) {
1016 dy = SkIntToScalar(srcIR.fTop);
1017 }
1018 if (dx || dy) {
1019 matrix.preTranslate(dx, dy);
1020 }
1021 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001022 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001023}
1024
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001025void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001026 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001027 if (d.fClip->isEmpty()) {
1028 return;
1029 }
1030
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001031 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001032 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001033 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1034 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001035}
1036
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001037void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001038 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001039 if (d.fClip->isEmpty()) {
1040 return;
1041 }
1042
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001043 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001044 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001045 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1046 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001047}
1048
halcanarybb264b72015-04-07 10:40:03 -07001049// Create a PDF string. Maximum length (in bytes) is 65,535.
1050// @param input A string value.
1051// @param len The length of the input array.
1052// @param wideChars True iff the upper byte in each uint16_t is
1053// significant and should be encoded and not
1054// discarded. If true, the upper byte is encoded
1055// first. Otherwise, we assert the upper byte is
1056// zero.
1057static SkString format_wide_string(const uint16_t* input,
1058 size_t len,
1059 bool wideChars) {
1060 if (wideChars) {
1061 SkASSERT(2 * len < 65535);
1062 static const char gHex[] = "0123456789ABCDEF";
1063 SkString result(4 * len + 2);
1064 result[0] = '<';
1065 for (size_t i = 0; i < len; i++) {
1066 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1067 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1068 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1069 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1070 }
1071 result[4 * len + 1] = '>';
1072 return result;
1073 } else {
1074 SkASSERT(len <= 65535);
1075 SkString tmp(len);
1076 for (size_t i = 0; i < len; i++) {
1077 SkASSERT(0 == input[i] >> 8);
1078 tmp[i] = static_cast<uint8_t>(input[i]);
1079 }
halcanarybc4696b2015-05-06 10:56:04 -07001080 return SkPDFUtils::FormatString(tmp.c_str(), tmp.size());
halcanarybb264b72015-04-07 10:40:03 -07001081 }
1082}
1083
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001084void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001085 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001086 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1087 if (paint.getMaskFilter() != NULL) {
1088 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1089 // making text unreadable (e.g. same text twice when using CSS shadows).
1090 return;
1091 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001092 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001093 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001094 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001095 return;
1096 }
1097
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001098 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001099 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001100 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001101 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001102
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001103 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001104 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001105 content.entry()->fContent.writeText("BT\n");
1106 set_text_transform(x, y, textPaint.getTextSkewX(),
1107 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001108 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001109
1110 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1111
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001112 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001113 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1114 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001115
1116 int availableGlyphs = font->glyphsToPDFFontEncoding(
1117 glyphIDsCopy.begin() + consumedGlyphCount,
1118 numGlyphs - consumedGlyphCount);
1119 fFontGlyphUsage->noteGlyphUsage(
1120 font, glyphIDsCopy.begin() + consumedGlyphCount,
1121 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001122 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001123 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1124 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001125 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001126 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001127 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001128 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001129 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001130}
1131
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001132void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001133 const SkScalar pos[], int scalarsPerPos,
1134 const SkPoint& offset, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001135 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1136 if (paint.getMaskFilter() != NULL) {
1137 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1138 // making text unreadable (e.g. same text twice when using CSS shadows).
1139 return;
1140 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001141 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001142 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001143 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001144 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001145 return;
1146 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001147
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001148 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001149 const uint16_t* glyphIDs = NULL;
1150 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001151 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001152
1153 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001154 content.entry()->fContent.writeText("BT\n");
1155 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001156 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001157 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001158 uint16_t encodedValue = glyphIDs[i];
1159 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001160 // The current pdf font cannot encode the current glyph.
1161 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001162 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001163 font = content.entry()->fState.fFont;
1164 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1165 SkDEBUGFAIL("PDF could not encode glyph.");
1166 continue;
1167 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001168 }
bungeman22edc832014-10-03 07:55:58 -07001169
vandebo@chromium.org98594282011-07-25 22:34:12 +00001170 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001171 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1172 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1173
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001174 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001175 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001176 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001177 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001178 content.entry()->fContent.writeText(encodedString.c_str());
1179 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001180 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001181 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001182}
1183
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001184void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001185 int vertexCount, const SkPoint verts[],
1186 const SkPoint texs[], const SkColor colors[],
1187 SkXfermode* xmode, const uint16_t indices[],
1188 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001189 if (d.fClip->isEmpty()) {
1190 return;
1191 }
reed@google.com85e143c2013-12-30 15:51:25 +00001192 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001193}
1194
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001195void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1196 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001197 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001198 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001199 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001200 return;
1201 }
1202
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001203 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001204 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001205 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001206 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001207 return;
1208 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001209 if (content.needShape()) {
1210 SkPath shape;
1211 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001212 SkIntToScalar(device->width()),
1213 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001214 content.setShape(shape);
1215 }
1216 if (!content.needSource()) {
1217 return;
1218 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001219
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001220 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1221 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001222 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001223
1224 // Merge glyph sets from the drawn device.
1225 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001226}
1227
reed89443ab2014-06-27 11:34:19 -07001228SkImageInfo SkPDFDevice::imageInfo() const {
1229 return fLegacyBitmap.info();
1230}
1231
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001232void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1233 INHERITED::onAttachToCanvas(canvas);
1234
1235 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1236 fClipStack = canvas->getClipStack();
1237}
1238
1239void SkPDFDevice::onDetachFromCanvas() {
1240 INHERITED::onDetachFromCanvas();
1241
1242 fClipStack = NULL;
1243}
1244
reed4a8126e2014-09-22 07:29:03 -07001245SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1246 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001247}
1248
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001249ContentEntry* SkPDFDevice::getLastContentEntry() {
1250 if (fDrawingArea == kContent_DrawingArea) {
1251 return fLastContentEntry;
1252 } else {
1253 return fLastMarginContentEntry;
1254 }
1255}
1256
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001257SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001258 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001259 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001260 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001261 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001262 }
1263}
1264
1265void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1266 if (fDrawingArea == kContent_DrawingArea) {
1267 fLastContentEntry = contentEntry;
1268 } else {
1269 fLastMarginContentEntry = contentEntry;
1270 }
1271}
1272
1273void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001274 // A ScopedContentEntry only exists during the course of a draw call, so
1275 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001276 fDrawingArea = drawingArea;
1277}
1278
halcanary2b861552015-04-09 13:27:40 -07001279SkPDFDict* SkPDFDevice::createResourceDict() const {
1280 SkTDArray<SkPDFObject*> fonts;
1281 fonts.setReserve(fFontResources.count());
1282 for (SkPDFFont* font : fFontResources) {
1283 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001284 }
halcanary2b861552015-04-09 13:27:40 -07001285 return SkPDFResourceDict::Create(
1286 &fGraphicStateResources,
1287 &fShaderResources,
1288 &fXObjectResources,
1289 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001290}
1291
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001292const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1293 return fFontResources;
1294}
1295
reed@google.com2a006c12012-09-19 17:05:55 +00001296SkPDFArray* SkPDFDevice::copyMediaBox() const {
1297 // should this be a singleton?
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001298
halcanary130444f2015-04-25 06:45:07 -07001299 SkAutoTUnref<SkPDFArray> mediaBox(SkNEW(SkPDFArray));
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001300 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001301 mediaBox->appendInt(0);
1302 mediaBox->appendInt(0);
reed@google.comc789cf12011-07-20 12:14:33 +00001303 mediaBox->appendInt(fPageSize.fWidth);
1304 mediaBox->appendInt(fPageSize.fHeight);
halcanary130444f2015-04-25 06:45:07 -07001305 return mediaBox.detach();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001306}
1307
halcanary334fcbc2015-02-24 12:56:16 -08001308SkStreamAsset* SkPDFDevice::content() const {
1309 SkDynamicMemoryWStream buffer;
1310 this->writeContent(&buffer);
1311 return buffer.detachAsStream();
reed@google.com5667afc2011-06-27 14:42:15 +00001312}
1313
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001314void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1315 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001316 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1317 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001318 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001319 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001320 SkPoint translation;
1321 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001322 translation.negate();
1323 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1324 translation);
1325 gsState.updateMatrix(entry->fState.fMatrix);
1326 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001327
halcanary7af21502015-02-23 12:17:59 -08001328 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001329 entry = entry->fNext.get();
1330 }
1331 gsState.drainStack();
1332}
1333
halcanary334fcbc2015-02-24 12:56:16 -08001334void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001335 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001336 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001337 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001338
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001339 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1340 // colors the contentArea white before it starts drawing into it and
1341 // that currently acts as our clip.
1342 // Also, think about adding a transform here (or assume that the values
1343 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001344 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001345
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001346 // If the content area is the entire page, then we don't need to clip
1347 // the content area (PDF area clips to the page size). Otherwise,
1348 // we have to clip to the content area; we've already applied the
1349 // initial transform, so just clip to the device size.
1350 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001351 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1352 SkIntToScalar(this->height()));
halcanary334fcbc2015-02-24 12:56:16 -08001353 emit_clip(NULL, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001354 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001355
halcanary334fcbc2015-02-24 12:56:16 -08001356 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001357}
1358
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001359/* Draws an inverse filled path by using Path Ops to compute the positive
1360 * inverse using the current clip as the inverse bounds.
1361 * Return true if this was an inverse path and was properly handled,
1362 * otherwise returns false and the normal drawing routine should continue,
1363 * either as a (incorrect) fallback or because the path was not inverse
1364 * in the first place.
1365 */
1366bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001367 const SkPaint& paint, bool pathIsMutable,
1368 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001369 if (!origPath.isInverseFillType()) {
1370 return false;
1371 }
1372
1373 if (d.fClip->isEmpty()) {
1374 return false;
1375 }
1376
1377 SkPath modifiedPath;
1378 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1379 SkPaint noInversePaint(paint);
1380
1381 // Merge stroking operations into final path.
1382 if (SkPaint::kStroke_Style == paint.getStyle() ||
1383 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1384 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1385 if (doFillPath) {
1386 noInversePaint.setStyle(SkPaint::kFill_Style);
1387 noInversePaint.setStrokeWidth(0);
1388 pathPtr = &modifiedPath;
1389 } else {
1390 // To be consistent with the raster output, hairline strokes
1391 // are rendered as non-inverted.
1392 modifiedPath.toggleInverseFillType();
1393 drawPath(d, modifiedPath, paint, NULL, true);
1394 return true;
1395 }
1396 }
1397
1398 // Get bounds of clip in current transform space
1399 // (clip bounds are given in device space).
1400 SkRect bounds;
1401 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001402 SkMatrix totalMatrix = *d.fMatrix;
1403 if (prePathMatrix) {
1404 totalMatrix.preConcat(*prePathMatrix);
1405 }
1406 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001407 return false;
1408 }
1409 bounds.set(d.fClip->getBounds());
1410 transformInverse.mapRect(&bounds);
1411
1412 // Extend the bounds by the line width (plus some padding)
1413 // so the edge doesn't cause a visible stroke.
1414 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1415 paint.getStrokeWidth() + SK_Scalar1);
1416
1417 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1418 return false;
1419 }
1420
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001421 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001422 return true;
1423}
1424
epoger@google.comb58772f2013-03-08 09:09:10 +00001425bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1426 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001427 SkAnnotation* annotationInfo = p.getAnnotation();
1428 if (!annotationInfo) {
1429 return false;
1430 }
1431 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001432 if (urlData) {
1433 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001434 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001435 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001436 SkData* linkToName = annotationInfo->find(
1437 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001438 if (linkToName) {
1439 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001440 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001441 }
1442 return false;
1443}
1444
1445bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1446 const SkMatrix& matrix,
1447 const SkPaint& paint) {
1448 SkAnnotation* annotationInfo = paint.getAnnotation();
1449 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001450 return false;
1451 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001452 SkData* nameData = annotationInfo->find(
1453 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001454 if (nameData) {
1455 for (size_t i = 0; i < count; i++) {
1456 defineNamedDestination(nameData, points[i], matrix);
1457 }
reed@google.com44699382013-10-31 17:28:30 +00001458 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001459 }
1460 return false;
1461}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001462
halcanary438de492015-04-28 06:21:01 -07001463void SkPDFDevice::addAnnotation(SkPDFDict* annotation) {
reed@google.com2a006c12012-09-19 17:05:55 +00001464 if (NULL == fAnnotations) {
1465 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001466 }
halcanary438de492015-04-28 06:21:01 -07001467 fAnnotations->appendObject(annotation);
1468}
1469
1470static SkPDFDict* create_link_annotation(const SkRect& r,
1471 const SkMatrix& initialTransform,
1472 const SkMatrix& matrix) {
1473 SkMatrix transform = matrix;
1474 transform.postConcat(initialTransform);
1475 SkRect translatedRect;
1476 transform.mapRect(&translatedRect, r);
1477
1478 SkAutoTUnref<SkPDFDict> annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001479 annotation->insertName("Subtype", "Link");
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001480
epoger@google.comb58772f2013-03-08 09:09:10 +00001481 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001482 border->reserve(3);
1483 border->appendInt(0); // Horizontal corner radius.
1484 border->appendInt(0); // Vertical corner radius.
1485 border->appendInt(0); // Width, 0 = no border.
halcanary438de492015-04-28 06:21:01 -07001486 annotation->insertObject("Border", border.detach());
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001487
epoger@google.comb58772f2013-03-08 09:09:10 +00001488 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001489 rect->reserve(4);
1490 rect->appendScalar(translatedRect.fLeft);
1491 rect->appendScalar(translatedRect.fTop);
1492 rect->appendScalar(translatedRect.fRight);
1493 rect->appendScalar(translatedRect.fBottom);
halcanary438de492015-04-28 06:21:01 -07001494 annotation->insertObject("Rect", rect.detach());
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001495
halcanary438de492015-04-28 06:21:01 -07001496 return annotation.detach();
epoger@google.comb58772f2013-03-08 09:09:10 +00001497}
epoger@google.com1cad8982013-03-06 00:05:13 +00001498
epoger@google.comb58772f2013-03-08 09:09:10 +00001499void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1500 const SkMatrix& matrix) {
halcanary438de492015-04-28 06:21:01 -07001501 SkAutoTUnref<SkPDFDict> annotation(
1502 create_link_annotation(r, fInitialTransform, matrix));
epoger@google.comb58772f2013-03-08 09:09:10 +00001503
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");
halcanary130444f2015-04-25 06:45:07 -07001508 action->insertString("URI", url);
halcanary438de492015-04-28 06:21:01 -07001509 annotation->insertObject("A", action.detach());
1510 this->addAnnotation(annotation.detach());
epoger@google.comb58772f2013-03-08 09:09:10 +00001511}
1512
1513void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1514 const SkMatrix& matrix) {
halcanary438de492015-04-28 06:21:01 -07001515 SkAutoTUnref<SkPDFDict> annotation(
1516 create_link_annotation(r, fInitialTransform, matrix));
epoger@google.comb58772f2013-03-08 09:09:10 +00001517 SkString name(static_cast<const char *>(nameData->data()),
1518 nameData->size() - 1);
halcanary130444f2015-04-25 06:45:07 -07001519 annotation->insertName("Dest", name);
halcanary438de492015-04-28 06:21:01 -07001520 this->addAnnotation(annotation.detach());
epoger@google.comb58772f2013-03-08 09:09:10 +00001521}
1522
1523struct NamedDestination {
1524 const SkData* nameData;
1525 SkPoint point;
1526
1527 NamedDestination(const SkData* nameData, const SkPoint& point)
halcanary130444f2015-04-25 06:45:07 -07001528 : nameData(SkRef(nameData)), point(point) {}
epoger@google.comb58772f2013-03-08 09:09:10 +00001529
1530 ~NamedDestination() {
1531 nameData->unref();
1532 }
1533};
1534
1535void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1536 const SkMatrix& matrix) {
1537 SkMatrix transform = matrix;
1538 transform.postConcat(fInitialTransform);
1539 SkPoint translatedPoint;
1540 transform.mapXY(point.x(), point.y(), &translatedPoint);
1541 fNamedDestinations.push(
1542 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1543}
1544
halcanary6d622702015-03-25 08:45:42 -07001545void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
epoger@google.comb58772f2013-03-08 09:09:10 +00001546 int nDest = fNamedDestinations.count();
1547 for (int i = 0; i < nDest; i++) {
1548 NamedDestination* dest = fNamedDestinations[i];
1549 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1550 pdfDest->reserve(5);
halcanary130444f2015-04-25 06:45:07 -07001551 pdfDest->appendObjRef(SkRef(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001552 pdfDest->appendName("XYZ");
1553 pdfDest->appendScalar(dest->point.x());
1554 pdfDest->appendScalar(dest->point.y());
1555 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary130444f2015-04-25 06:45:07 -07001556 SkString name(static_cast<const char*>(dest->nameData->data()));
1557 dict->insertObject(name, pdfDest.detach());
epoger@google.comb58772f2013-03-08 09:09:10 +00001558 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001559}
1560
reed@google.comfc641d02012-09-20 17:52:20 +00001561SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1562 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001563 // We always draw the form xobjects that we create back into the device, so
1564 // we simply preserve the font usage instead of pulling it out and merging
1565 // it back in later.
1566 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001567 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001568 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001569}
1570
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001571void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1572 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001573 const SkClipStack* clipStack,
1574 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001575 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001576 bool invertClip) {
1577 if (clipRegion.isEmpty() && !invertClip) {
1578 return;
1579 }
1580
halcanarybe27a112015-04-01 13:31:19 -07001581 SkAutoTUnref<SkPDFObject> sMaskGS(SkPDFGraphicState::GetSMaskGraphicState(
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001582 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1583
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001584 SkMatrix identity;
1585 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001586 SkPaint paint;
1587 paint.setXfermodeMode(mode);
1588 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001589 if (!content.entry()) {
1590 return;
1591 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001592 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001593 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001594 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001595
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001596 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001597 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001598 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001599}
1600
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001601ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1602 const SkRegion& clipRegion,
1603 const SkMatrix& matrix,
1604 const SkPaint& paint,
1605 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001606 SkPDFFormXObject** dst) {
1607 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001608 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001609 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001610 }
1611
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001612 // The clip stack can come from an SkDraw where it is technically optional.
1613 SkClipStack synthesizedClipStack;
1614 if (clipStack == NULL) {
1615 if (clipRegion == fExistingClipRegion) {
1616 clipStack = &fExistingClipStack;
1617 } else {
1618 // GraphicStackState::updateClip expects the clip stack to have
1619 // fExistingClip as a prefix, so start there, then set the clip
1620 // to the passed region.
1621 synthesizedClipStack = fExistingClipStack;
1622 SkPath clipPath;
1623 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001624 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1625 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001626 clipStack = &synthesizedClipStack;
1627 }
1628 }
1629
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001630 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1631 if (paint.getXfermode()) {
1632 paint.getXfermode()->asMode(&xfermode);
1633 }
1634
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001635 // For the following modes, we want to handle source and destination
1636 // separately, so make an object of what's already there.
1637 if (xfermode == SkXfermode::kClear_Mode ||
1638 xfermode == SkXfermode::kSrc_Mode ||
1639 xfermode == SkXfermode::kSrcIn_Mode ||
1640 xfermode == SkXfermode::kDstIn_Mode ||
1641 xfermode == SkXfermode::kSrcOut_Mode ||
1642 xfermode == SkXfermode::kDstOut_Mode ||
1643 xfermode == SkXfermode::kSrcATop_Mode ||
1644 xfermode == SkXfermode::kDstATop_Mode ||
1645 xfermode == SkXfermode::kModulate_Mode) {
1646 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001647 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001648 SkASSERT(isContentEmpty());
1649 } else if (xfermode != SkXfermode::kSrc_Mode &&
1650 xfermode != SkXfermode::kSrcOut_Mode) {
1651 // Except for Src and SrcOut, if there isn't anything already there,
1652 // then we're done.
1653 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001654 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001655 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001656 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001657 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001658
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001659 // Dst xfer mode doesn't draw source at all.
1660 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001661 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001662 }
1663
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001664 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001665 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001666
1667 ContentEntry* lastContentEntry = getLastContentEntry();
1668 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1669 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001670 } else {
1671 newEntry.reset(new ContentEntry);
1672 entry = newEntry.get();
1673 }
1674
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001675 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001676 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001677 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1678 entry->fState.compareInitialState(lastContentEntry->fState)) {
1679 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001680 }
1681
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001682 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001683 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001684 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001685 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001686 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001687 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001688 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001689 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001690 lastContentEntry->fNext.reset(entry);
1691 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001692 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001693 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001694 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001695}
1696
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001697void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001698 SkPDFFormXObject* dst,
1699 SkPath* shape) {
1700 if (xfermode != SkXfermode::kClear_Mode &&
1701 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001702 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001703 xfermode != SkXfermode::kSrcIn_Mode &&
1704 xfermode != SkXfermode::kDstIn_Mode &&
1705 xfermode != SkXfermode::kSrcOut_Mode &&
1706 xfermode != SkXfermode::kDstOut_Mode &&
1707 xfermode != SkXfermode::kSrcATop_Mode &&
1708 xfermode != SkXfermode::kDstATop_Mode &&
1709 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001710 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001711 return;
1712 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001713 if (xfermode == SkXfermode::kDstOver_Mode) {
1714 SkASSERT(!dst);
1715 ContentEntry* firstContentEntry = getContentEntries()->get();
1716 if (firstContentEntry->fContent.getOffset() == 0) {
1717 // For DstOver, an empty content entry was inserted before the rest
1718 // of the content entries. If nothing was drawn, it needs to be
1719 // removed.
1720 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1721 contentEntries->reset(firstContentEntry->fNext.detach());
1722 }
1723 return;
1724 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001725 if (!dst) {
1726 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1727 xfermode == SkXfermode::kSrcOut_Mode);
1728 return;
1729 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001730
1731 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001732 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001733 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001734 // Changing the current content into a form-xobject will destroy the clip
1735 // objects which is fine since the xobject will already be clipped. However
1736 // if source has shape, we need to clip it too, so a copy of the clip is
1737 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001738 SkClipStack clipStack = contentEntries->fState.fClipStack;
1739 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001740
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001741 SkMatrix identity;
1742 identity.reset();
1743 SkPaint stockPaint;
1744
reed@google.comfc641d02012-09-20 17:52:20 +00001745 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001746 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001747 // If nothing was drawn and there's no shape, then the draw was a
1748 // no-op, but dst needs to be restored for that to be true.
1749 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1750 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1751 // reduces to Dst.
1752 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1753 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001754 ScopedContentEntry content(this, &fExistingClipStack,
1755 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001756 stockPaint);
1757 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1758 &content.entry()->fContent);
1759 return;
1760 } else {
1761 xfermode = SkXfermode::kClear_Mode;
1762 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001763 } else {
1764 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001765 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001766 }
1767
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001768 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1769 // without alpha.
1770 if (xfermode == SkXfermode::kSrcATop_Mode) {
1771 // TODO(vandebo): In order to properly support SrcATop we have to track
1772 // the shape of what's been drawn at all times. It's the intersection of
1773 // the non-transparent parts of the device and the outlines (shape) of
1774 // all images and devices drawn.
1775 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001776 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001777 SkXfermode::kSrcOver_Mode, true);
1778 } else {
1779 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1780 SkPDFFormXObject* dstMask = srcFormXObject.get();
1781 if (shape != NULL) {
1782 // Draw shape into a form-xobject.
1783 SkDraw d;
1784 d.fMatrix = &identity;
1785 d.fClip = &clipRegion;
1786 d.fClipStack = &clipStack;
1787 SkPaint filledPaint;
1788 filledPaint.setColor(SK_ColorBLACK);
1789 filledPaint.setStyle(SkPaint::kFill_Style);
1790 this->drawPath(d, *shape, filledPaint, NULL, true);
1791
1792 dstMaskStorage.reset(createFormXObjectFromDevice());
1793 dstMask = dstMaskStorage.get();
1794 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001795 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1796 &fExistingClipStack, fExistingClipRegion,
1797 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001798 }
1799
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001800 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001801 return;
1802 } else if (xfermode == SkXfermode::kSrc_Mode ||
1803 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001804 ScopedContentEntry content(this, &fExistingClipStack,
1805 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001806 if (content.entry()) {
1807 SkPDFUtils::DrawFormXObject(
1808 this->addXObjectResource(srcFormXObject.get()),
1809 &content.entry()->fContent);
1810 }
1811 if (xfermode == SkXfermode::kSrc_Mode) {
1812 return;
1813 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001814 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001815 ScopedContentEntry content(this, &fExistingClipStack,
1816 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001817 if (content.entry()) {
1818 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1819 &content.entry()->fContent);
1820 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001821 }
1822
1823 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1824 xfermode == SkXfermode::kDstIn_Mode ||
1825 xfermode == SkXfermode::kSrcOut_Mode ||
1826 xfermode == SkXfermode::kDstOut_Mode ||
1827 xfermode == SkXfermode::kSrcATop_Mode ||
1828 xfermode == SkXfermode::kDstATop_Mode ||
1829 xfermode == SkXfermode::kModulate_Mode);
1830
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001831 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001832 xfermode == SkXfermode::kSrcOut_Mode ||
1833 xfermode == SkXfermode::kSrcATop_Mode) {
1834 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001835 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001836 SkXfermode::kSrcOver_Mode,
1837 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001838 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001839 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1840 if (xfermode == SkXfermode::kModulate_Mode) {
1841 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001842 dst, &fExistingClipStack,
1843 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001844 SkXfermode::kSrcOver_Mode, false);
1845 mode = SkXfermode::kMultiply_Mode;
1846 }
1847 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001848 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001849 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001850 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001851}
1852
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001853bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001854 ContentEntry* contentEntries = getContentEntries()->get();
1855 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1856 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001857 return true;
1858 }
1859 return false;
1860}
1861
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001862void SkPDFDevice::populateGraphicStateEntryFromPaint(
1863 const SkMatrix& matrix,
1864 const SkClipStack& clipStack,
1865 const SkRegion& clipRegion,
1866 const SkPaint& paint,
1867 bool hasText,
1868 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001869 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001870 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1871 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001872
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001873 entry->fMatrix = matrix;
1874 entry->fClipStack = clipStack;
1875 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001876 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1877 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001878
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001879 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001880 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001881 const SkShader* shader = paint.getShader();
1882 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001883 if (shader) {
1884 // PDF positions patterns relative to the initial transform, so
1885 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001886 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001887 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001888
1889 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001890 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001891 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001892
1893 // We need to apply the initial transform to bounds in order to get
1894 // bounds in a consistent coordinate system.
1895 SkRect boundsTemp;
1896 boundsTemp.set(bounds);
1897 fInitialTransform.mapRect(&boundsTemp);
1898 boundsTemp.roundOut(&bounds);
1899
halcanary792c80f2015-02-20 07:21:05 -08001900 SkScalar rasterScale =
1901 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
1902 pdfShader.reset(SkPDFShader::GetPDFShader(
1903 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001904
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001905 if (pdfShader.get()) {
1906 // pdfShader has been canonicalized so we can directly compare
1907 // pointers.
1908 int resourceIndex = fShaderResources.find(pdfShader.get());
1909 if (resourceIndex < 0) {
1910 resourceIndex = fShaderResources.count();
1911 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001912 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001913 }
1914 entry->fShaderIndex = resourceIndex;
1915 } else {
1916 // A color shader is treated as an invalid shader so we don't have
1917 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001918 SkShader::GradientInfo gradientInfo;
1919 SkColor gradientColor;
1920 gradientInfo.fColors = &gradientColor;
1921 gradientInfo.fColorOffsets = NULL;
1922 gradientInfo.fColorCount = 1;
1923 if (shader->asAGradient(&gradientInfo) ==
1924 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001925 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1926 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001927 }
1928 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001929 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001930
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001931 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001932 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001933 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001934 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001935 } else {
1936 SkPaint newPaint = paint;
1937 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001938 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001939 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001940 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001941 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001942 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001943
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001944 if (hasText) {
1945 entry->fTextScaleX = paint.getTextScaleX();
1946 entry->fTextFill = paint.getStyle();
1947 } else {
1948 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001949 }
1950}
1951
halcanarybe27a112015-04-01 13:31:19 -07001952int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001953 // Assumes that gs has been canonicalized (so we can directly compare
1954 // pointers).
1955 int result = fGraphicStateResources.find(gs);
1956 if (result < 0) {
1957 result = fGraphicStateResources.count();
1958 fGraphicStateResources.push(gs);
1959 gs->ref();
1960 }
1961 return result;
1962}
1963
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001964int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
1965 // Assumes that xobject has been canonicalized (so we can directly compare
1966 // pointers).
1967 int result = fXObjectResources.find(xObject);
1968 if (result < 0) {
1969 result = fXObjectResources.count();
1970 fXObjectResources.push(xObject);
1971 xObject->ref();
1972 }
1973 return result;
1974}
1975
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001976void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
1977 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001978 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001979 if (contentEntry->fState.fFont == NULL ||
1980 contentEntry->fState.fTextSize != paint.getTextSize() ||
1981 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001982 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001983 contentEntry->fContent.writeText("/");
1984 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
1985 SkPDFResourceDict::kFont_ResourceType,
1986 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001987 contentEntry->fContent.writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -07001988 SkPDFUtils::AppendScalar(paint.getTextSize(), &contentEntry->fContent);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001989 contentEntry->fContent.writeText(" Tf\n");
1990 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001991 }
1992}
1993
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001994int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary792c80f2015-02-20 07:21:05 -08001995 SkAutoTUnref<SkPDFFont> newFont(
1996 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001997 int resourceIndex = fFontResources.find(newFont.get());
1998 if (resourceIndex < 0) {
1999 resourceIndex = fFontResources.count();
2000 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002001 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002002 }
2003 return resourceIndex;
2004}
2005
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002006void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002007 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002008 const SkRegion& origClipRegion,
2009 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002010 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002011 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002012 SkMatrix matrix = origMatrix;
2013 SkRegion perspectiveBounds;
2014 const SkRegion* clipRegion = &origClipRegion;
2015 SkBitmap perspectiveBitmap;
2016 const SkBitmap* bitmap = &origBitmap;
2017 SkBitmap tmpSubsetBitmap;
2018
2019 // Rasterize the bitmap using perspective in a new bitmap.
2020 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002021 if (fRasterDpi == 0) {
2022 return;
2023 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002024 SkBitmap* subsetBitmap;
2025 if (srcRect) {
2026 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2027 return;
2028 }
2029 subsetBitmap = &tmpSubsetBitmap;
2030 } else {
2031 subsetBitmap = &tmpSubsetBitmap;
2032 *subsetBitmap = origBitmap;
2033 }
2034 srcRect = NULL;
2035
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002036 // Transform the bitmap in the new space, without taking into
2037 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002038 SkPath perspectiveOutline;
2039 perspectiveOutline.addRect(
2040 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2041 SkIntToScalar(subsetBitmap->height())));
2042 perspectiveOutline.transform(origMatrix);
2043
2044 // TODO(edisonn): perf - use current clip too.
2045 // Retrieve the bounds of the new shape.
2046 SkRect bounds = perspectiveOutline.getBounds();
2047
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002048 // Transform the bitmap in the new space, taking into
2049 // account the initial transform.
2050 SkMatrix total = origMatrix;
2051 total.postConcat(fInitialTransform);
2052 total.postScale(SkIntToScalar(fRasterDpi) /
2053 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2054 SkIntToScalar(fRasterDpi) /
2055 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2056 SkPath physicalPerspectiveOutline;
2057 physicalPerspectiveOutline.addRect(
2058 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2059 SkIntToScalar(subsetBitmap->height())));
2060 physicalPerspectiveOutline.transform(total);
2061
2062 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2063 bounds.width();
2064 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2065 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002066
2067 // TODO(edisonn): A better approach would be to use a bitmap shader
2068 // (in clamp mode) and draw a rect over the entire bounding box. Then
2069 // intersect perspectiveOutline to the clip. That will avoid introducing
2070 // alpha to the image while still giving good behavior at the edge of
2071 // the image. Avoiding alpha will reduce the pdf size and generation
2072 // CPU time some.
2073
reed@google.com9ebcac52014-01-24 18:53:42 +00002074 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2075 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002076 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002077 return;
2078 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002079 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2080
reed89443ab2014-06-27 11:34:19 -07002081 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002082
2083 SkScalar deltaX = bounds.left();
2084 SkScalar deltaY = bounds.top();
2085
2086 SkMatrix offsetMatrix = origMatrix;
2087 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002088 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002089
2090 // Translate the draw in the new canvas, so we perfectly fit the
2091 // shape in the bitmap.
2092 canvas.setMatrix(offsetMatrix);
2093
2094 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2095
2096 // Make sure the final bits are in the bitmap.
2097 canvas.flush();
2098
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002099 // In the new space, we use the identity matrix translated
2100 // and scaled to reflect DPI.
2101 matrix.setScale(1 / scaleX, 1 / scaleY);
2102 matrix.postTranslate(deltaX, deltaY);
2103
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002104 perspectiveBounds.setRect(
2105 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2106 SkScalarFloorToInt(bounds.y()),
2107 SkScalarCeilToInt(bounds.width()),
2108 SkScalarCeilToInt(bounds.height())));
2109 clipRegion = &perspectiveBounds;
2110 srcRect = NULL;
2111 bitmap = &perspectiveBitmap;
2112 }
2113
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002114 SkMatrix scaled;
2115 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002116 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2117 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002118 // Scale the image up from 1x1 to WxH.
halcanaryf622a6c2014-10-24 12:54:53 -07002119 SkIRect subset = bitmap->bounds();
reed@google.coma6d59f62011-03-07 21:29:21 +00002120 scaled.postScale(SkIntToScalar(subset.width()),
2121 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002122 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002123 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002124 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2125 return;
2126 }
2127 if (content.needShape()) {
2128 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002129 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
halcanarydb0dcc72015-03-20 12:31:52 -07002130 SkIntToScalar(subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002131 shape.transform(matrix);
2132 content.setShape(shape);
2133 }
2134 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002135 return;
2136 }
2137
halcanarydb0dcc72015-03-20 12:31:52 -07002138 SkBitmap subsetBitmap;
2139 // Should extractSubset be done by the SkPDFDevice?
2140 if (!bitmap->extractSubset(&subsetBitmap, subset)) {
2141 return;
2142 }
2143 SkAutoTUnref<SkPDFObject> image(SkPDFBitmap::Create(fCanon, subsetBitmap));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002144 if (!image) {
2145 return;
2146 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002147
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002148 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002149 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002150}