blob: 736c50b9a6d8b0151ca8fbd7c1f445b545078883 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000015#include "SkFontHost.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000016#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000018#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
23#include "SkPDFImage.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000024#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000026#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000029#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000030#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000031#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070032#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000033#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000034#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000035#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000036#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000037
edisonn@google.com73a7ea32013-11-11 20:55:15 +000038#define DPI_FOR_RASTER_SCALE_ONE 72
39
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000040// Utility functions
41
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000042static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000043 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
44 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000045 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000046 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
47 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000048 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000049 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
50 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000051 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000052 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
53 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000054}
55
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000056static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000057 SkPaint result = paint;
58 if (result.isFakeBoldText()) {
59 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
60 kStdFakeBoldInterpKeys,
61 kStdFakeBoldInterpValues,
62 kStdFakeBoldInterpLength);
63 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000064 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000065 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000066 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000067 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000068 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000069 result.setStrokeWidth(width);
70 }
71 return result;
72}
73
74// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000075static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000076 const uint16_t* glyphs, size_t len,
77 SkScalar* x, SkScalar* y) {
78 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000079 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000080 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000081
82 SkMatrix ident;
83 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000084 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000085 SkGlyphCache* cache = autoCache.getCache();
86
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000087 const char* start = reinterpret_cast<const char*>(glyphs);
88 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000089 SkFixed xAdv = 0, yAdv = 0;
90
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000091 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000092 while (start < stop) {
93 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
94 xAdv += glyph.fAdvanceX;
95 yAdv += glyph.fAdvanceY;
96 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000097 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000098 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000099 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000100
101 SkScalar xAdj = SkFixedToScalar(xAdv);
102 SkScalar yAdj = SkFixedToScalar(yAdv);
103 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
104 xAdj = SkScalarHalf(xAdj);
105 yAdj = SkScalarHalf(yAdj);
106 }
107 *x = *x - xAdj;
108 *y = *y - yAdj;
109}
110
robertphillips@google.coma4662862013-11-21 14:24:16 +0000111static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000112 SkAutoResolveDefaultTypeface autoResolve(typeface);
113 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000114 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000115}
116
117typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
118
reed@google.comaec40662014-04-18 19:29:07 +0000119static int force_glyph_encoding(const SkPaint& paint, const void* text,
120 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700121 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000122 // Make sure we have a glyph id encoding.
123 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
reed@google.comaec40662014-04-18 19:29:07 +0000124 int numGlyphs = paint.textToGlyphs(text, len, NULL);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000125 storage->reset(numGlyphs);
126 paint.textToGlyphs(text, len, storage->get());
127 *glyphIDs = storage->get();
128 return numGlyphs;
129 }
130
131 // For user supplied glyph ids we need to validate them.
132 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000133 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700134 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000135
136 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000137 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000138 for (validated = 0; validated < numGlyphs; ++validated) {
139 if (input[validated] > maxGlyphID) {
140 break;
141 }
142 }
143 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700144 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000145 return numGlyphs;
146 }
147
148 // Silently drop anything out of range.
149 storage->reset(numGlyphs);
150 if (validated > 0) {
151 memcpy(storage->get(), input, validated * sizeof(uint16_t));
152 }
153
reed@google.comaec40662014-04-18 19:29:07 +0000154 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000155 storage->get()[i] = input[i];
156 if (input[i] > maxGlyphID) {
157 storage->get()[i] = 0;
158 }
159 }
160 *glyphIDs = storage->get();
161 return numGlyphs;
162}
163
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000164static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
165 SkWStream* content) {
166 // Flip the text about the x-axis to account for origin swap and include
167 // the passed parameters.
168 content->writeText("1 0 ");
169 SkPDFScalar::Append(0 - textSkewX, content);
170 content->writeText(" -1 ");
171 SkPDFScalar::Append(x, content);
172 content->writeText(" ");
173 SkPDFScalar::Append(y, content);
174 content->writeText(" Tm\n");
175}
176
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000177// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
178// later being our representation of an object in the PDF file.
179struct GraphicStateEntry {
180 GraphicStateEntry();
181
182 // Compare the fields we care about when setting up a new content entry.
183 bool compareInitialState(const GraphicStateEntry& b);
184
185 SkMatrix fMatrix;
186 // We can't do set operations on Paths, though PDF natively supports
187 // intersect. If the clip stack does anything other than intersect,
188 // we have to fall back to the region. Treat fClipStack as authoritative.
189 // See http://code.google.com/p/skia/issues/detail?id=221
190 SkClipStack fClipStack;
191 SkRegion fClipRegion;
192
193 // When emitting the content entry, we will ensure the graphic state
194 // is set to these values first.
195 SkColor fColor;
196 SkScalar fTextScaleX; // Zero means we don't care what the value is.
197 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
198 int fShaderIndex;
199 int fGraphicStateIndex;
200
201 // We may change the font (i.e. for Type1 support) within a
202 // ContentEntry. This is the one currently in effect, or NULL if none.
203 SkPDFFont* fFont;
204 // In PDF, text size has no default value. It is only valid if fFont is
205 // not NULL.
206 SkScalar fTextSize;
207};
208
209GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
210 fTextScaleX(SK_Scalar1),
211 fTextFill(SkPaint::kFill_Style),
212 fShaderIndex(-1),
213 fGraphicStateIndex(-1),
214 fFont(NULL),
215 fTextSize(SK_ScalarNaN) {
216 fMatrix.reset();
217}
218
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000219bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
220 return fColor == cur.fColor &&
221 fShaderIndex == cur.fShaderIndex &&
222 fGraphicStateIndex == cur.fGraphicStateIndex &&
223 fMatrix == cur.fMatrix &&
224 fClipStack == cur.fClipStack &&
225 (fTextScaleX == 0 ||
226 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000227}
228
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000229class GraphicStackState {
230public:
231 GraphicStackState(const SkClipStack& existingClipStack,
232 const SkRegion& existingClipRegion,
233 SkWStream* contentStream)
234 : fStackDepth(0),
235 fContentStream(contentStream) {
236 fEntries[0].fClipStack = existingClipStack;
237 fEntries[0].fClipRegion = existingClipRegion;
238 }
239
240 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000241 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000242 void updateMatrix(const SkMatrix& matrix);
243 void updateDrawingState(const GraphicStateEntry& state);
244
245 void drainStack();
246
247private:
248 void push();
249 void pop();
250 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
251
252 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
253 static const int kMaxStackDepth = 12;
254 GraphicStateEntry fEntries[kMaxStackDepth + 1];
255 int fStackDepth;
256 SkWStream* fContentStream;
257};
258
259void GraphicStackState::drainStack() {
260 while (fStackDepth) {
261 pop();
262 }
263}
264
265void GraphicStackState::push() {
266 SkASSERT(fStackDepth < kMaxStackDepth);
267 fContentStream->writeText("q\n");
268 fStackDepth++;
269 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
270}
271
272void GraphicStackState::pop() {
273 SkASSERT(fStackDepth > 0);
274 fContentStream->writeText("Q\n");
275 fStackDepth--;
276}
277
robertphillips@google.com80214e22012-07-20 15:33:18 +0000278// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000279// and then skips over the leading entries as specified in prefix. It requires
280// and asserts that "prefix" will be a prefix to "stack."
281static void skip_clip_stack_prefix(const SkClipStack& prefix,
282 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000283 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000284 SkClipStack::B2TIter prefixIter(prefix);
285 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000286
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000287 const SkClipStack::Element* prefixEntry;
288 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000289
290 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000291 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000292 iterEntry = iter->next();
293 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000294 // Because of SkClipStack does internal intersection, the last clip
295 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000296 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000297 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
298 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
299 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000300 // back up the iterator by one
301 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000302 prefixEntry = prefixIter.next();
303 break;
304 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000305 }
306
307 SkASSERT(prefixEntry == NULL);
308}
309
310static void emit_clip(SkPath* clipPath, SkRect* clipRect,
311 SkWStream* contentStream) {
312 SkASSERT(clipPath || clipRect);
313
314 SkPath::FillType clipFill;
315 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000316 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000317 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000318 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000319 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
320 clipFill = SkPath::kWinding_FillType;
321 }
322
323 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
324 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
325 if (clipFill == SkPath::kEvenOdd_FillType) {
326 contentStream->writeText("W* n\n");
327 } else {
328 contentStream->writeText("W n\n");
329 }
330}
331
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000332#ifdef SK_PDF_USE_PATHOPS
333/* Calculate an inverted path's equivalent non-inverted path, given the
334 * canvas bounds.
335 * outPath may alias with invPath (since this is supported by PathOps).
336 */
337static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
338 SkPath* outPath) {
339 SkASSERT(invPath.isInverseFillType());
340
341 SkPath clipPath;
342 clipPath.addRect(bounds);
343
344 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
345}
346
347// Sanity check the numerical values of the SkRegion ops and PathOps ops
348// enums so region_op_to_pathops_op can do a straight passthrough cast.
349// If these are failing, it may be necessary to make region_op_to_pathops_op
350// do more.
351SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
352 region_pathop_mismatch);
353SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
354 region_pathop_mismatch);
355SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
356 region_pathop_mismatch);
357SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
358 region_pathop_mismatch);
359SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
360 (int)kReverseDifference_PathOp,
361 region_pathop_mismatch);
362
363static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
364 SkASSERT(op >= 0);
365 SkASSERT(op <= SkRegion::kReverseDifference_Op);
366 return (SkPathOp)op;
367}
368
369/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
370 * Returns true if successful, or false if not successful.
371 * If successful, the resulting clip is stored in outClipPath.
372 * If not successful, outClipPath is undefined, and a fallback method
373 * should be used.
374 */
375static bool get_clip_stack_path(const SkMatrix& transform,
376 const SkClipStack& clipStack,
377 const SkRegion& clipRegion,
378 SkPath* outClipPath) {
379 outClipPath->reset();
380 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
381
382 const SkClipStack::Element* clipEntry;
383 SkClipStack::Iter iter;
384 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
385 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
386 SkPath entryPath;
387 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
388 outClipPath->reset();
389 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
390 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000391 } else {
392 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000393 }
394 entryPath.transform(transform);
395
396 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
397 *outClipPath = entryPath;
398 } else {
399 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
400 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
401 return false;
402 }
403 }
404 }
405
406 if (outClipPath->isInverseFillType()) {
407 // The bounds are slightly outset to ensure this is correct in the
408 // face of floating-point accuracy and possible SkRegion bitmap
409 // approximations.
410 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
411 clipBounds.outset(SK_Scalar1, SK_Scalar1);
412 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
413 return false;
414 }
415 }
416 return true;
417}
418#endif
419
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000420// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000421// graphic state stack, and the fact that we can know all the clips used
422// on the page to optimize this.
423void GraphicStackState::updateClip(const SkClipStack& clipStack,
424 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000425 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000426 if (clipStack == currentEntry()->fClipStack) {
427 return;
428 }
429
430 while (fStackDepth > 0) {
431 pop();
432 if (clipStack == currentEntry()->fClipStack) {
433 return;
434 }
435 }
436 push();
437
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000438 currentEntry()->fClipStack = clipStack;
439 currentEntry()->fClipRegion = clipRegion;
440
441 SkMatrix transform;
442 transform.setTranslate(translation.fX, translation.fY);
443
444#ifdef SK_PDF_USE_PATHOPS
445 SkPath clipPath;
446 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
447 emit_clip(&clipPath, NULL, fContentStream);
448 return;
449 }
450#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000451 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
452 // already been applied. (If this is a top level device, then it specifies
453 // a clip to the content area. If this is a layer, then it specifies
454 // the clip in effect when the layer was created.) There's no need to
455 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
456 // initial clip on the parent layer. (This means there's a bug if the user
457 // expands the clip and then uses any xfer mode that uses dst:
458 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000459 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000460 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
461
462 // If the clip stack does anything other than intersect or if it uses
463 // an inverse fill type, we have to fall back to the clip region.
464 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000465 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000466 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000467 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
468 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000469 needRegion = true;
470 break;
471 }
472 }
473
474 if (needRegion) {
475 SkPath clipPath;
476 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
477 emit_clip(&clipPath, NULL, fContentStream);
478 } else {
479 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000480 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000481 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000482 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
483 switch (clipEntry->getType()) {
484 case SkClipStack::Element::kRect_Type: {
485 SkRect translatedClip;
486 transform.mapRect(&translatedClip, clipEntry->getRect());
487 emit_clip(NULL, &translatedClip, fContentStream);
488 break;
489 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000490 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000491 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000492 clipEntry->asPath(&translatedPath);
493 translatedPath.transform(transform, &translatedPath);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000494 emit_clip(&translatedPath, NULL, fContentStream);
495 break;
496 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000497 }
498 }
499 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000500}
501
502void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
503 if (matrix == currentEntry()->fMatrix) {
504 return;
505 }
506
507 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
508 SkASSERT(fStackDepth > 0);
509 SkASSERT(fEntries[fStackDepth].fClipStack ==
510 fEntries[fStackDepth -1].fClipStack);
511 pop();
512
513 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
514 }
515 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
516 return;
517 }
518
519 push();
520 SkPDFUtils::AppendTransform(matrix, fContentStream);
521 currentEntry()->fMatrix = matrix;
522}
523
524void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
525 // PDF treats a shader as a color, so we only set one or the other.
526 if (state.fShaderIndex >= 0) {
527 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000528 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000529 currentEntry()->fShaderIndex = state.fShaderIndex;
530 }
531 } else {
532 if (state.fColor != currentEntry()->fColor ||
533 currentEntry()->fShaderIndex >= 0) {
534 emit_pdf_color(state.fColor, fContentStream);
535 fContentStream->writeText("RG ");
536 emit_pdf_color(state.fColor, fContentStream);
537 fContentStream->writeText("rg\n");
538 currentEntry()->fColor = state.fColor;
539 currentEntry()->fShaderIndex = -1;
540 }
541 }
542
543 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000544 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000545 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
546 }
547
548 if (state.fTextScaleX) {
549 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
550 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
551 SkIntToScalar(100));
552 SkPDFScalar::Append(pdfScale, fContentStream);
553 fContentStream->writeText(" Tz\n");
554 currentEntry()->fTextScaleX = state.fTextScaleX;
555 }
556 if (state.fTextFill != currentEntry()->fTextFill) {
557 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
558 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
559 enum_must_match_value);
560 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
561 enum_must_match_value);
562 fContentStream->writeDecAsText(state.fTextFill);
563 fContentStream->writeText(" Tr\n");
564 currentEntry()->fTextFill = state.fTextFill;
565 }
566 }
567}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000568
commit-bot@chromium.org15a14052014-02-16 00:59:25 +0000569SkBaseDevice* SkPDFDevice::onCreateDevice(const SkImageInfo& info, Usage usage) {
bsalomon@google.come97f0852011-06-17 13:10:25 +0000570 SkMatrix initialTransform;
571 initialTransform.reset();
commit-bot@chromium.org15a14052014-02-16 00:59:25 +0000572 SkISize size = SkISize::Make(info.width(), info.height());
bsalomon@google.come97f0852011-06-17 13:10:25 +0000573 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
574}
575
576
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000577struct ContentEntry {
578 GraphicStateEntry fState;
579 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000580 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000581
582 // If the stack is too deep we could get Stack Overflow.
583 // So we manually destruct the object.
584 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000585 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000586 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000587 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000588 // When the destructor is called, fNext is NULL and exits.
589 delete val;
590 val = valNext;
591 }
592 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000593};
594
595// A helper class to automatically finish a ContentEntry at the end of a
596// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000597class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000598public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000599 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
600 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000601 : fDevice(device),
602 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000603 fXfermode(SkXfermode::kSrcOver_Mode),
604 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000605 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
606 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000607 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
608 const SkRegion& clipRegion, const SkMatrix& matrix,
609 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000610 : fDevice(device),
611 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000612 fXfermode(SkXfermode::kSrcOver_Mode),
613 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000614 init(clipStack, clipRegion, matrix, paint, hasText);
615 }
616
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000617 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000619 SkPath* shape = &fShape;
620 if (shape->isEmpty()) {
621 shape = NULL;
622 }
623 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000624 }
reed@google.comfc641d02012-09-20 17:52:20 +0000625 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000626 }
627
628 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000629
630 /* Returns true when we explicitly need the shape of the drawing. */
631 bool needShape() {
632 switch (fXfermode) {
633 case SkXfermode::kClear_Mode:
634 case SkXfermode::kSrc_Mode:
635 case SkXfermode::kSrcIn_Mode:
636 case SkXfermode::kSrcOut_Mode:
637 case SkXfermode::kDstIn_Mode:
638 case SkXfermode::kDstOut_Mode:
639 case SkXfermode::kSrcATop_Mode:
640 case SkXfermode::kDstATop_Mode:
641 case SkXfermode::kModulate_Mode:
642 return true;
643 default:
644 return false;
645 }
646 }
647
648 /* Returns true unless we only need the shape of the drawing. */
649 bool needSource() {
650 if (fXfermode == SkXfermode::kClear_Mode) {
651 return false;
652 }
653 return true;
654 }
655
656 /* If the shape is different than the alpha component of the content, then
657 * setShape should be called with the shape. In particular, images and
658 * devices have rectangular shape.
659 */
660 void setShape(const SkPath& shape) {
661 fShape = shape;
662 }
663
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000664private:
665 SkPDFDevice* fDevice;
666 ContentEntry* fContentEntry;
667 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000668 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000669 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000670
671 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
672 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000673 // Shape has to be flatten before we get here.
674 if (matrix.hasPerspective()) {
675 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000676 return;
677 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000678 if (paint.getXfermode()) {
679 paint.getXfermode()->asMode(&fXfermode);
680 }
681 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
682 matrix, paint, hasText,
683 &fDstFormXObject);
684 }
685};
686
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000687////////////////////////////////////////////////////////////////////////////////
688
reed89443ab2014-06-27 11:34:19 -0700689static inline SkImageInfo make_content_info(const SkISize& contentSize,
690 const SkMatrix* initialTransform) {
reed@google.com900ecf22014-02-20 20:55:37 +0000691 SkImageInfo info;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000692 if (initialTransform) {
693 // Compute the size of the drawing area.
694 SkVector drawingSize;
695 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000696 drawingSize.set(SkIntToScalar(contentSize.fWidth),
697 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000698 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000699 // This shouldn't happen, initial transform should be invertible.
700 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000701 inverse.reset();
702 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000703 inverse.mapVectors(&drawingSize, 1);
704 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
reed@google.com900ecf22014-02-20 20:55:37 +0000705 info = SkImageInfo::MakeUnknown(abs(size.fWidth), abs(size.fHeight));
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000706 } else {
reed@google.com900ecf22014-02-20 20:55:37 +0000707 info = SkImageInfo::MakeUnknown(abs(contentSize.fWidth),
708 abs(contentSize.fHeight));
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000709 }
reed89443ab2014-06-27 11:34:19 -0700710 return info;
reed@android.comf2b98d62010-12-20 18:26:13 +0000711}
712
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000713// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000714SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000715 const SkMatrix& initialTransform)
reed89443ab2014-06-27 11:34:19 -0700716 : fPageSize(pageSize)
717 , fContentSize(contentSize)
718 , fLastContentEntry(NULL)
719 , fLastMarginContentEntry(NULL)
720 , fClipStack(NULL)
721 , fEncoder(NULL)
722 , fRasterDpi(72.0f)
723{
724 const SkImageInfo info = make_content_info(contentSize, &initialTransform);
725
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000726 // Just report that PDF does not supports perspective in the
727 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000728 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
729
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000730 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000731 // origin at the bottom left. This matrix corrects for that. But that only
732 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000733 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
734 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000735 fInitialTransform.preConcat(initialTransform);
reed89443ab2014-06-27 11:34:19 -0700736 fLegacyBitmap.setInfo(info);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000737
reed89443ab2014-06-27 11:34:19 -0700738 SkIRect existingClip = SkIRect::MakeWH(info.width(), info.height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000739 fExistingClipRegion.setRect(existingClip);
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000740 this->init();
741}
742
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000743// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000744SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
745 const SkClipStack& existingClipStack,
746 const SkRegion& existingClipRegion)
reed89443ab2014-06-27 11:34:19 -0700747 : fPageSize(layerSize)
748 , fContentSize(layerSize)
749 , fExistingClipStack(existingClipStack)
750 , fExistingClipRegion(existingClipRegion)
751 , fLastContentEntry(NULL)
752 , fLastMarginContentEntry(NULL)
753 , fClipStack(NULL)
754 , fEncoder(NULL)
755 , fRasterDpi(72.0f)
756{
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000757 fInitialTransform.reset();
reed89443ab2014-06-27 11:34:19 -0700758 fLegacyBitmap.setInfo(make_content_info(layerSize, NULL));
759
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000760 this->init();
761}
762
763SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000764 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000765}
766
767void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000768 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000769 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000770 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000771 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000772 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000773 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000774 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000775 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000776 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
777 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000778}
779
vandebo@chromium.org98594282011-07-25 22:34:12 +0000780void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000781 fGraphicStateResources.unrefAll();
782 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000783 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000784 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000785 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000786 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000787 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000788
vandebo@chromium.org98594282011-07-25 22:34:12 +0000789 if (clearFontUsage) {
790 fFontGlyphUsage->reset();
791 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000792}
793
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000794void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000795 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000796 this->init();
797
798 SkPaint paint;
799 paint.setColor(color);
800 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000801 SkMatrix identity;
802 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000803 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
804 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000805 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000806}
807
808void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000809 SkPaint newPaint = paint;
810 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000811 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000812 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000813}
814
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000815void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
816 ContentEntry* contentEntry) {
817 if (!contentEntry) {
818 return;
819 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000820 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
821 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000822 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000823 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000824 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000825 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000826 inverse.mapRect(&bbox);
827
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000828 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000829 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000830 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000831}
832
833void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
834 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000835 const SkPaint& passedPaint) {
836 if (count == 0) {
837 return;
838 }
839
epoger@google.comb58772f2013-03-08 09:09:10 +0000840 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
841 return;
842 }
843
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000844 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
845 // We only use this when there's a path effect because of the overhead
846 // of multiple calls to setUpContentEntry it causes.
847 if (passedPaint.getPathEffect()) {
848 if (d.fClip->isEmpty()) {
849 return;
850 }
851 SkDraw pointDraw(d);
852 pointDraw.fDevice = this;
853 pointDraw.drawPoints(mode, count, points, passedPaint, true);
854 return;
855 }
856
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000857 const SkPaint* paint = &passedPaint;
858 SkPaint modifiedPaint;
859
860 if (mode == SkCanvas::kPoints_PointMode &&
861 paint->getStrokeCap() != SkPaint::kRound_Cap) {
862 modifiedPaint = *paint;
863 paint = &modifiedPaint;
864 if (paint->getStrokeWidth()) {
865 // PDF won't draw a single point with square/butt caps because the
866 // orientation is ambiguous. Draw a rectangle instead.
867 modifiedPaint.setStyle(SkPaint::kFill_Style);
868 SkScalar strokeWidth = paint->getStrokeWidth();
869 SkScalar halfStroke = SkScalarHalf(strokeWidth);
870 for (size_t i = 0; i < count; i++) {
871 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
872 r.inset(-halfStroke, -halfStroke);
873 drawRect(d, r, modifiedPaint);
874 }
875 return;
876 } else {
877 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
878 }
879 }
880
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000881 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000882 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000883 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000884 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000885
886 switch (mode) {
887 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000888 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000889 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000890 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000891 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000892 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000893 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000894 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000895 break;
896 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000897 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000898 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000899 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000900 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000901 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000902 &content.entry()->fContent);
903 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000904 }
905 break;
906 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000907 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
908 for (size_t i = 0; i < count; i++) {
909 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000910 &content.entry()->fContent);
911 SkPDFUtils::ClosePath(&content.entry()->fContent);
912 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000913 }
914 break;
915 default:
916 SkASSERT(false);
917 }
918}
919
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000920void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000921 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000922 SkRect r = rect;
923 r.sort();
924
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000925 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000926 if (d.fClip->isEmpty()) {
927 return;
928 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000929 SkPath path;
930 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000931 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000932 return;
933 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000934
epoger@google.comb58772f2013-03-08 09:09:10 +0000935 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000936 return;
937 }
938
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000939 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000940 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000941 return;
942 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000943 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000944 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000945 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000946}
947
reed89443ab2014-06-27 11:34:19 -0700948void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000949 SkPath path;
950 path.addRRect(rrect);
951 this->drawPath(draw, path, paint, NULL, true);
952}
953
reed89443ab2014-06-27 11:34:19 -0700954void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
955 SkPath path;
956 path.addOval(oval);
957 this->drawPath(draw, path, paint, NULL, true);
958}
959
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000960void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000961 const SkPaint& paint, const SkMatrix* prePathMatrix,
962 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000963 SkPath modifiedPath;
964 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
965
966 SkMatrix matrix = *d.fMatrix;
967 if (prePathMatrix) {
968 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
969 if (!pathIsMutable) {
970 pathPtr = &modifiedPath;
971 pathIsMutable = true;
972 }
973 origPath.transform(*prePathMatrix, pathPtr);
974 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000975 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000976 }
977 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000978
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000979 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000980 if (d.fClip->isEmpty()) {
981 return;
982 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000983 if (!pathIsMutable) {
984 pathPtr = &modifiedPath;
985 pathIsMutable = true;
986 }
987 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000988
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000989 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000990 noEffectPaint.setPathEffect(NULL);
991 if (fill) {
992 noEffectPaint.setStyle(SkPaint::kFill_Style);
993 } else {
994 noEffectPaint.setStyle(SkPaint::kStroke_Style);
995 noEffectPaint.setStrokeWidth(0);
996 }
997 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000998 return;
999 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001000
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001001#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001002 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001003 return;
1004 }
1005#endif
1006
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001007 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001008 return;
1009 }
1010
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001011 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001012 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001013 return;
1014 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001015 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1016 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001017 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001018 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001019}
1020
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001021void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1022 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001023 const SkPaint& paint,
1024 SkCanvas::DrawBitmapRectFlags flags) {
1025 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001026 SkMatrix matrix;
1027 SkRect bitmapBounds, tmpSrc, tmpDst;
1028 SkBitmap tmpBitmap;
1029
1030 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1031
1032 // Compute matrix from the two rectangles
1033 if (src) {
1034 tmpSrc = *src;
1035 } else {
1036 tmpSrc = bitmapBounds;
1037 }
1038 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1039
1040 const SkBitmap* bitmapPtr = &bitmap;
1041
1042 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1043 // needed (if the src was clipped). No check needed if src==null.
1044 if (src) {
1045 if (!bitmapBounds.contains(*src)) {
1046 if (!tmpSrc.intersect(bitmapBounds)) {
1047 return; // nothing to draw
1048 }
1049 // recompute dst, based on the smaller tmpSrc
1050 matrix.mapRect(&tmpDst, tmpSrc);
1051 }
1052
1053 // since we may need to clamp to the borders of the src rect within
1054 // the bitmap, we extract a subset.
1055 // TODO: make sure this is handled in drawBitmap and remove from here.
1056 SkIRect srcIR;
1057 tmpSrc.roundOut(&srcIR);
1058 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1059 return;
1060 }
1061 bitmapPtr = &tmpBitmap;
1062
1063 // Since we did an extract, we need to adjust the matrix accordingly
1064 SkScalar dx = 0, dy = 0;
1065 if (srcIR.fLeft > 0) {
1066 dx = SkIntToScalar(srcIR.fLeft);
1067 }
1068 if (srcIR.fTop > 0) {
1069 dy = SkIntToScalar(srcIR.fTop);
1070 }
1071 if (dx || dy) {
1072 matrix.preTranslate(dx, dy);
1073 }
1074 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001075 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001076}
1077
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001078void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001079 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001080 if (d.fClip->isEmpty()) {
1081 return;
1082 }
1083
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001084 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001085 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001086 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1087 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001088}
1089
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001090void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001091 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001092 if (d.fClip->isEmpty()) {
1093 return;
1094 }
1095
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001096 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001097 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001098 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1099 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001100}
1101
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001102void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001103 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001104 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1105 if (paint.getMaskFilter() != NULL) {
1106 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1107 // making text unreadable (e.g. same text twice when using CSS shadows).
1108 return;
1109 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001110 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001111 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001112 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001113 return;
1114 }
1115
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001116 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001117 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001118 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001119 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001120
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001121 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001122 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001123 content.entry()->fContent.writeText("BT\n");
1124 set_text_transform(x, y, textPaint.getTextSkewX(),
1125 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001126 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001127
1128 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1129
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001130 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001131 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1132 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001133
1134 int availableGlyphs = font->glyphsToPDFFontEncoding(
1135 glyphIDsCopy.begin() + consumedGlyphCount,
1136 numGlyphs - consumedGlyphCount);
1137 fFontGlyphUsage->noteGlyphUsage(
1138 font, glyphIDsCopy.begin() + consumedGlyphCount,
1139 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001140 SkString encodedString =
halcanary2f912f32014-10-16 09:53:20 -07001141 SkPDFString::FormatString(glyphIDsCopy.begin() + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001142 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001143 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001144 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001145 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001146 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001147 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001148}
1149
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001150void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001151 const SkScalar pos[], int scalarsPerPos,
1152 const SkPoint& offset, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001153 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1154 if (paint.getMaskFilter() != NULL) {
1155 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1156 // making text unreadable (e.g. same text twice when using CSS shadows).
1157 return;
1158 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001159 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001160 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001161 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001162 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001163 return;
1164 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001165
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001166 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001167 const uint16_t* glyphIDs = NULL;
1168 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001169 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001170
1171 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001172 content.entry()->fContent.writeText("BT\n");
1173 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001174 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001175 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001176 uint16_t encodedValue = glyphIDs[i];
1177 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001178 // The current pdf font cannot encode the current glyph.
1179 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001180 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001181 font = content.entry()->fState.fFont;
1182 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1183 SkDEBUGFAIL("PDF could not encode glyph.");
1184 continue;
1185 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001186 }
bungeman22edc832014-10-03 07:55:58 -07001187
vandebo@chromium.org98594282011-07-25 22:34:12 +00001188 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001189 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1190 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1191
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001192 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001193 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001194 SkString encodedString =
bungeman22edc832014-10-03 07:55:58 -07001195 SkPDFString::FormatString(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001196 content.entry()->fContent.writeText(encodedString.c_str());
1197 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001198 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001199 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001200}
1201
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001202void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001203 const SkPath& path, const SkMatrix* matrix,
1204 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001205 if (d.fClip->isEmpty()) {
1206 return;
1207 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001208 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001209}
1210
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001211void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001212 int vertexCount, const SkPoint verts[],
1213 const SkPoint texs[], const SkColor colors[],
1214 SkXfermode* xmode, const uint16_t indices[],
1215 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001216 if (d.fClip->isEmpty()) {
1217 return;
1218 }
reed@google.com85e143c2013-12-30 15:51:25 +00001219 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001220}
1221
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001222void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1223 int x, int y, const SkPaint& paint) {
commit-bot@chromium.org3da3b622014-03-13 19:38:10 +00001224 // our onCreateDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001225 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001226 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001227 return;
1228 }
1229
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001230 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001231 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001232 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001233 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001234 return;
1235 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001236 if (content.needShape()) {
1237 SkPath shape;
1238 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001239 SkIntToScalar(device->width()),
1240 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001241 content.setShape(shape);
1242 }
1243 if (!content.needSource()) {
1244 return;
1245 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001246
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001247 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1248 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001249 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001250
1251 // Merge glyph sets from the drawn device.
1252 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001253}
1254
reed89443ab2014-06-27 11:34:19 -07001255SkImageInfo SkPDFDevice::imageInfo() const {
1256 return fLegacyBitmap.info();
1257}
1258
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001259void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1260 INHERITED::onAttachToCanvas(canvas);
1261
1262 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1263 fClipStack = canvas->getClipStack();
1264}
1265
1266void SkPDFDevice::onDetachFromCanvas() {
1267 INHERITED::onDetachFromCanvas();
1268
1269 fClipStack = NULL;
1270}
1271
reed4a8126e2014-09-22 07:29:03 -07001272SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1273 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001274}
1275
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001276ContentEntry* SkPDFDevice::getLastContentEntry() {
1277 if (fDrawingArea == kContent_DrawingArea) {
1278 return fLastContentEntry;
1279 } else {
1280 return fLastMarginContentEntry;
1281 }
1282}
1283
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001284SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001285 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001286 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001287 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001288 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001289 }
1290}
1291
1292void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1293 if (fDrawingArea == kContent_DrawingArea) {
1294 fLastContentEntry = contentEntry;
1295 } else {
1296 fLastMarginContentEntry = contentEntry;
1297 }
1298}
1299
1300void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001301 // A ScopedContentEntry only exists during the course of a draw call, so
1302 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001303 fDrawingArea = drawingArea;
1304}
1305
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001306SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001307 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001308 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001309
1310 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001311 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001312 fResourceDict->insertResourceAsReference(
1313 SkPDFResourceDict::kExtGState_ResourceType,
1314 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001315 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001316 }
1317
1318 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001319 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001320 fResourceDict->insertResourceAsReference(
1321 SkPDFResourceDict::kXObject_ResourceType,
1322 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001323 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001324 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001325
1326 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001327 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001328 fResourceDict->insertResourceAsReference(
1329 SkPDFResourceDict::kFont_ResourceType,
1330 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001331 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001332 }
1333
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001334 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001335 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001336 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001337 fResourceDict->insertResourceAsReference(
1338 SkPDFResourceDict::kPattern_ResourceType,
1339 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001340 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001341 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001342 }
1343 return fResourceDict;
1344}
1345
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001346const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1347 return fFontResources;
1348}
1349
reed@google.com2a006c12012-09-19 17:05:55 +00001350SkPDFArray* SkPDFDevice::copyMediaBox() const {
1351 // should this be a singleton?
1352 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001353
reed@google.com2a006c12012-09-19 17:05:55 +00001354 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001355 mediaBox->reserve(4);
1356 mediaBox->append(zero.get());
1357 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001358 mediaBox->appendInt(fPageSize.fWidth);
1359 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001360 return mediaBox;
1361}
1362
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001363SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001364 SkMemoryStream* result = new SkMemoryStream;
1365 result->setData(this->copyContentToData())->unref();
1366 return result;
1367}
1368
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001369void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1370 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001371 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1372 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001373 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001374 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001375 SkPoint translation;
1376 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001377 translation.negate();
1378 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1379 translation);
1380 gsState.updateMatrix(entry->fState.fMatrix);
1381 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001382
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001383 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001384 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001385 entry = entry->fNext.get();
1386 }
1387 gsState.drainStack();
1388}
1389
reed@google.com5667afc2011-06-27 14:42:15 +00001390SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001391 SkDynamicMemoryWStream data;
1392 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1393 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001394 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001395
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001396 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1397 // colors the contentArea white before it starts drawing into it and
1398 // that currently acts as our clip.
1399 // Also, think about adding a transform here (or assume that the values
1400 // sent across account for that)
1401 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001402
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001403 // If the content area is the entire page, then we don't need to clip
1404 // the content area (PDF area clips to the page size). Otherwise,
1405 // we have to clip to the content area; we've already applied the
1406 // initial transform, so just clip to the device size.
1407 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001408 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1409 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001410 emit_clip(NULL, &r, &data);
1411 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001412
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001413 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001414
reed@google.com5667afc2011-06-27 14:42:15 +00001415 // potentially we could cache this SkData, and only rebuild it if we
1416 // see that our state has changed.
1417 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001418}
1419
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001420#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001421/* Draws an inverse filled path by using Path Ops to compute the positive
1422 * inverse using the current clip as the inverse bounds.
1423 * Return true if this was an inverse path and was properly handled,
1424 * otherwise returns false and the normal drawing routine should continue,
1425 * either as a (incorrect) fallback or because the path was not inverse
1426 * in the first place.
1427 */
1428bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001429 const SkPaint& paint, bool pathIsMutable,
1430 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001431 if (!origPath.isInverseFillType()) {
1432 return false;
1433 }
1434
1435 if (d.fClip->isEmpty()) {
1436 return false;
1437 }
1438
1439 SkPath modifiedPath;
1440 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1441 SkPaint noInversePaint(paint);
1442
1443 // Merge stroking operations into final path.
1444 if (SkPaint::kStroke_Style == paint.getStyle() ||
1445 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1446 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1447 if (doFillPath) {
1448 noInversePaint.setStyle(SkPaint::kFill_Style);
1449 noInversePaint.setStrokeWidth(0);
1450 pathPtr = &modifiedPath;
1451 } else {
1452 // To be consistent with the raster output, hairline strokes
1453 // are rendered as non-inverted.
1454 modifiedPath.toggleInverseFillType();
1455 drawPath(d, modifiedPath, paint, NULL, true);
1456 return true;
1457 }
1458 }
1459
1460 // Get bounds of clip in current transform space
1461 // (clip bounds are given in device space).
1462 SkRect bounds;
1463 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001464 SkMatrix totalMatrix = *d.fMatrix;
1465 if (prePathMatrix) {
1466 totalMatrix.preConcat(*prePathMatrix);
1467 }
1468 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001469 return false;
1470 }
1471 bounds.set(d.fClip->getBounds());
1472 transformInverse.mapRect(&bounds);
1473
1474 // Extend the bounds by the line width (plus some padding)
1475 // so the edge doesn't cause a visible stroke.
1476 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1477 paint.getStrokeWidth() + SK_Scalar1);
1478
1479 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1480 return false;
1481 }
1482
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001483 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001484 return true;
1485}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001486#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001487
epoger@google.comb58772f2013-03-08 09:09:10 +00001488bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1489 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001490 SkAnnotation* annotationInfo = p.getAnnotation();
1491 if (!annotationInfo) {
1492 return false;
1493 }
1494 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001495 if (urlData) {
1496 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001497 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001498 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001499 SkData* linkToName = annotationInfo->find(
1500 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001501 if (linkToName) {
1502 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001503 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001504 }
1505 return false;
1506}
1507
1508bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1509 const SkMatrix& matrix,
1510 const SkPaint& paint) {
1511 SkAnnotation* annotationInfo = paint.getAnnotation();
1512 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001513 return false;
1514 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001515 SkData* nameData = annotationInfo->find(
1516 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001517 if (nameData) {
1518 for (size_t i = 0; i < count; i++) {
1519 defineNamedDestination(nameData, points[i], matrix);
1520 }
reed@google.com44699382013-10-31 17:28:30 +00001521 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001522 }
1523 return false;
1524}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001525
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001526SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1527 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001528 SkMatrix transform = matrix;
1529 transform.postConcat(fInitialTransform);
1530 SkRect translatedRect;
1531 transform.mapRect(&translatedRect, r);
1532
reed@google.com2a006c12012-09-19 17:05:55 +00001533 if (NULL == fAnnotations) {
1534 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001535 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001536 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001537 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001538 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001539
epoger@google.comb58772f2013-03-08 09:09:10 +00001540 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001541 border->reserve(3);
1542 border->appendInt(0); // Horizontal corner radius.
1543 border->appendInt(0); // Vertical corner radius.
1544 border->appendInt(0); // Width, 0 = no border.
1545 annotation->insert("Border", border.get());
1546
epoger@google.comb58772f2013-03-08 09:09:10 +00001547 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001548 rect->reserve(4);
1549 rect->appendScalar(translatedRect.fLeft);
1550 rect->appendScalar(translatedRect.fTop);
1551 rect->appendScalar(translatedRect.fRight);
1552 rect->appendScalar(translatedRect.fBottom);
1553 annotation->insert("Rect", rect.get());
1554
epoger@google.comb58772f2013-03-08 09:09:10 +00001555 return annotation;
1556}
epoger@google.com1cad8982013-03-06 00:05:13 +00001557
epoger@google.comb58772f2013-03-08 09:09:10 +00001558void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1559 const SkMatrix& matrix) {
1560 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1561
1562 SkString url(static_cast<const char *>(urlData->data()),
1563 urlData->size() - 1);
1564 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1565 action->insertName("S", "URI");
1566 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1567 annotation->insert("A", action.get());
1568}
1569
1570void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1571 const SkMatrix& matrix) {
1572 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1573 SkString name(static_cast<const char *>(nameData->data()),
1574 nameData->size() - 1);
1575 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1576}
1577
1578struct NamedDestination {
1579 const SkData* nameData;
1580 SkPoint point;
1581
1582 NamedDestination(const SkData* nameData, const SkPoint& point)
1583 : nameData(nameData), point(point) {
1584 nameData->ref();
1585 }
1586
1587 ~NamedDestination() {
1588 nameData->unref();
1589 }
1590};
1591
1592void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1593 const SkMatrix& matrix) {
1594 SkMatrix transform = matrix;
1595 transform.postConcat(fInitialTransform);
1596 SkPoint translatedPoint;
1597 transform.mapXY(point.x(), point.y(), &translatedPoint);
1598 fNamedDestinations.push(
1599 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1600}
1601
1602void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1603 int nDest = fNamedDestinations.count();
1604 for (int i = 0; i < nDest; i++) {
1605 NamedDestination* dest = fNamedDestinations[i];
1606 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1607 pdfDest->reserve(5);
1608 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1609 pdfDest->appendName("XYZ");
1610 pdfDest->appendScalar(dest->point.x());
1611 pdfDest->appendScalar(dest->point.y());
1612 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001613 dict->insert(static_cast<const char *>(dest->nameData->data()),
1614 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001615 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001616}
1617
reed@google.comfc641d02012-09-20 17:52:20 +00001618SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1619 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001620 // We always draw the form xobjects that we create back into the device, so
1621 // we simply preserve the font usage instead of pulling it out and merging
1622 // it back in later.
1623 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001624 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001625 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001626}
1627
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001628void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1629 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001630 const SkClipStack* clipStack,
1631 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001632 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001633 bool invertClip) {
1634 if (clipRegion.isEmpty() && !invertClip) {
1635 return;
1636 }
1637
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001638 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1639 SkPDFGraphicState::GetSMaskGraphicState(
1640 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1641
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001642 SkMatrix identity;
1643 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001644 SkPaint paint;
1645 paint.setXfermodeMode(mode);
1646 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001647 if (!content.entry()) {
1648 return;
1649 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001650 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001651 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001652 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001653
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001654 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001655 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001656 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001657}
1658
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001659ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1660 const SkRegion& clipRegion,
1661 const SkMatrix& matrix,
1662 const SkPaint& paint,
1663 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001664 SkPDFFormXObject** dst) {
1665 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001666 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001667 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001668 }
1669
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001670 // The clip stack can come from an SkDraw where it is technically optional.
1671 SkClipStack synthesizedClipStack;
1672 if (clipStack == NULL) {
1673 if (clipRegion == fExistingClipRegion) {
1674 clipStack = &fExistingClipStack;
1675 } else {
1676 // GraphicStackState::updateClip expects the clip stack to have
1677 // fExistingClip as a prefix, so start there, then set the clip
1678 // to the passed region.
1679 synthesizedClipStack = fExistingClipStack;
1680 SkPath clipPath;
1681 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001682 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1683 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001684 clipStack = &synthesizedClipStack;
1685 }
1686 }
1687
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001688 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1689 if (paint.getXfermode()) {
1690 paint.getXfermode()->asMode(&xfermode);
1691 }
1692
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001693 // For the following modes, we want to handle source and destination
1694 // separately, so make an object of what's already there.
1695 if (xfermode == SkXfermode::kClear_Mode ||
1696 xfermode == SkXfermode::kSrc_Mode ||
1697 xfermode == SkXfermode::kSrcIn_Mode ||
1698 xfermode == SkXfermode::kDstIn_Mode ||
1699 xfermode == SkXfermode::kSrcOut_Mode ||
1700 xfermode == SkXfermode::kDstOut_Mode ||
1701 xfermode == SkXfermode::kSrcATop_Mode ||
1702 xfermode == SkXfermode::kDstATop_Mode ||
1703 xfermode == SkXfermode::kModulate_Mode) {
1704 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001705 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001706 SkASSERT(isContentEmpty());
1707 } else if (xfermode != SkXfermode::kSrc_Mode &&
1708 xfermode != SkXfermode::kSrcOut_Mode) {
1709 // Except for Src and SrcOut, if there isn't anything already there,
1710 // then we're done.
1711 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001712 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001713 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001714 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001715 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001716
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001717 // Dst xfer mode doesn't draw source at all.
1718 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001719 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001720 }
1721
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001722 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001723 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001724
1725 ContentEntry* lastContentEntry = getLastContentEntry();
1726 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1727 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001728 } else {
1729 newEntry.reset(new ContentEntry);
1730 entry = newEntry.get();
1731 }
1732
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001733 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001734 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001735 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1736 entry->fState.compareInitialState(lastContentEntry->fState)) {
1737 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001738 }
1739
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001740 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001741 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001742 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001743 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001744 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001745 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001746 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001747 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001748 lastContentEntry->fNext.reset(entry);
1749 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001750 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001751 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001752 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001753}
1754
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001755void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001756 SkPDFFormXObject* dst,
1757 SkPath* shape) {
1758 if (xfermode != SkXfermode::kClear_Mode &&
1759 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001760 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001761 xfermode != SkXfermode::kSrcIn_Mode &&
1762 xfermode != SkXfermode::kDstIn_Mode &&
1763 xfermode != SkXfermode::kSrcOut_Mode &&
1764 xfermode != SkXfermode::kDstOut_Mode &&
1765 xfermode != SkXfermode::kSrcATop_Mode &&
1766 xfermode != SkXfermode::kDstATop_Mode &&
1767 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001768 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001769 return;
1770 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001771 if (xfermode == SkXfermode::kDstOver_Mode) {
1772 SkASSERT(!dst);
1773 ContentEntry* firstContentEntry = getContentEntries()->get();
1774 if (firstContentEntry->fContent.getOffset() == 0) {
1775 // For DstOver, an empty content entry was inserted before the rest
1776 // of the content entries. If nothing was drawn, it needs to be
1777 // removed.
1778 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1779 contentEntries->reset(firstContentEntry->fNext.detach());
1780 }
1781 return;
1782 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001783 if (!dst) {
1784 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1785 xfermode == SkXfermode::kSrcOut_Mode);
1786 return;
1787 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001788
1789 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001790 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001791 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001792 // Changing the current content into a form-xobject will destroy the clip
1793 // objects which is fine since the xobject will already be clipped. However
1794 // if source has shape, we need to clip it too, so a copy of the clip is
1795 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001796 SkClipStack clipStack = contentEntries->fState.fClipStack;
1797 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001798
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001799 SkMatrix identity;
1800 identity.reset();
1801 SkPaint stockPaint;
1802
reed@google.comfc641d02012-09-20 17:52:20 +00001803 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001804 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001805 // If nothing was drawn and there's no shape, then the draw was a
1806 // no-op, but dst needs to be restored for that to be true.
1807 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1808 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1809 // reduces to Dst.
1810 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1811 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001812 ScopedContentEntry content(this, &fExistingClipStack,
1813 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001814 stockPaint);
1815 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1816 &content.entry()->fContent);
1817 return;
1818 } else {
1819 xfermode = SkXfermode::kClear_Mode;
1820 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001821 } else {
1822 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001823 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001824 }
1825
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001826 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1827 // without alpha.
1828 if (xfermode == SkXfermode::kSrcATop_Mode) {
1829 // TODO(vandebo): In order to properly support SrcATop we have to track
1830 // the shape of what's been drawn at all times. It's the intersection of
1831 // the non-transparent parts of the device and the outlines (shape) of
1832 // all images and devices drawn.
1833 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001834 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001835 SkXfermode::kSrcOver_Mode, true);
1836 } else {
1837 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1838 SkPDFFormXObject* dstMask = srcFormXObject.get();
1839 if (shape != NULL) {
1840 // Draw shape into a form-xobject.
1841 SkDraw d;
1842 d.fMatrix = &identity;
1843 d.fClip = &clipRegion;
1844 d.fClipStack = &clipStack;
1845 SkPaint filledPaint;
1846 filledPaint.setColor(SK_ColorBLACK);
1847 filledPaint.setStyle(SkPaint::kFill_Style);
1848 this->drawPath(d, *shape, filledPaint, NULL, true);
1849
1850 dstMaskStorage.reset(createFormXObjectFromDevice());
1851 dstMask = dstMaskStorage.get();
1852 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001853 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1854 &fExistingClipStack, fExistingClipRegion,
1855 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001856 }
1857
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001858 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001859 return;
1860 } else if (xfermode == SkXfermode::kSrc_Mode ||
1861 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001862 ScopedContentEntry content(this, &fExistingClipStack,
1863 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001864 if (content.entry()) {
1865 SkPDFUtils::DrawFormXObject(
1866 this->addXObjectResource(srcFormXObject.get()),
1867 &content.entry()->fContent);
1868 }
1869 if (xfermode == SkXfermode::kSrc_Mode) {
1870 return;
1871 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001872 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001873 ScopedContentEntry content(this, &fExistingClipStack,
1874 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001875 if (content.entry()) {
1876 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1877 &content.entry()->fContent);
1878 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001879 }
1880
1881 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1882 xfermode == SkXfermode::kDstIn_Mode ||
1883 xfermode == SkXfermode::kSrcOut_Mode ||
1884 xfermode == SkXfermode::kDstOut_Mode ||
1885 xfermode == SkXfermode::kSrcATop_Mode ||
1886 xfermode == SkXfermode::kDstATop_Mode ||
1887 xfermode == SkXfermode::kModulate_Mode);
1888
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001889 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001890 xfermode == SkXfermode::kSrcOut_Mode ||
1891 xfermode == SkXfermode::kSrcATop_Mode) {
1892 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001893 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001894 SkXfermode::kSrcOver_Mode,
1895 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001896 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001897 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1898 if (xfermode == SkXfermode::kModulate_Mode) {
1899 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001900 dst, &fExistingClipStack,
1901 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001902 SkXfermode::kSrcOver_Mode, false);
1903 mode = SkXfermode::kMultiply_Mode;
1904 }
1905 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001906 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001907 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001908 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001909}
1910
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001911bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001912 ContentEntry* contentEntries = getContentEntries()->get();
1913 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1914 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001915 return true;
1916 }
1917 return false;
1918}
1919
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001920void SkPDFDevice::populateGraphicStateEntryFromPaint(
1921 const SkMatrix& matrix,
1922 const SkClipStack& clipStack,
1923 const SkRegion& clipRegion,
1924 const SkPaint& paint,
1925 bool hasText,
1926 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001927 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001928 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1929 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001930
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001931 entry->fMatrix = matrix;
1932 entry->fClipStack = clipStack;
1933 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001934 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1935 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001936
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001937 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001938 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001939 const SkShader* shader = paint.getShader();
1940 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001941 if (shader) {
1942 // PDF positions patterns relative to the initial transform, so
1943 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001944 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001945 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001946
1947 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001948 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001949 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001950
1951 // We need to apply the initial transform to bounds in order to get
1952 // bounds in a consistent coordinate system.
1953 SkRect boundsTemp;
1954 boundsTemp.set(bounds);
1955 fInitialTransform.mapRect(&boundsTemp);
1956 boundsTemp.roundOut(&bounds);
1957
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001958 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001959
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001960 if (pdfShader.get()) {
1961 // pdfShader has been canonicalized so we can directly compare
1962 // pointers.
1963 int resourceIndex = fShaderResources.find(pdfShader.get());
1964 if (resourceIndex < 0) {
1965 resourceIndex = fShaderResources.count();
1966 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001967 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001968 }
1969 entry->fShaderIndex = resourceIndex;
1970 } else {
1971 // A color shader is treated as an invalid shader so we don't have
1972 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001973 SkShader::GradientInfo gradientInfo;
1974 SkColor gradientColor;
1975 gradientInfo.fColors = &gradientColor;
1976 gradientInfo.fColorOffsets = NULL;
1977 gradientInfo.fColorCount = 1;
1978 if (shader->asAGradient(&gradientInfo) ==
1979 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001980 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1981 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001982 }
1983 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001984 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001985
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001986 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001987 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001988 newGraphicState.reset(
1989 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001990 } else {
1991 SkPaint newPaint = paint;
1992 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001993 newGraphicState.reset(
1994 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001995 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001996 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001997 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001998
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001999 if (hasText) {
2000 entry->fTextScaleX = paint.getTextScaleX();
2001 entry->fTextFill = paint.getStyle();
2002 } else {
2003 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002004 }
2005}
2006
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002007int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2008 // Assumes that gs has been canonicalized (so we can directly compare
2009 // pointers).
2010 int result = fGraphicStateResources.find(gs);
2011 if (result < 0) {
2012 result = fGraphicStateResources.count();
2013 fGraphicStateResources.push(gs);
2014 gs->ref();
2015 }
2016 return result;
2017}
2018
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002019int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2020 // Assumes that xobject has been canonicalized (so we can directly compare
2021 // pointers).
2022 int result = fXObjectResources.find(xObject);
2023 if (result < 0) {
2024 result = fXObjectResources.count();
2025 fXObjectResources.push(xObject);
2026 xObject->ref();
2027 }
2028 return result;
2029}
2030
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002031void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2032 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002033 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002034 if (contentEntry->fState.fFont == NULL ||
2035 contentEntry->fState.fTextSize != paint.getTextSize() ||
2036 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002037 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002038 contentEntry->fContent.writeText("/");
2039 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2040 SkPDFResourceDict::kFont_ResourceType,
2041 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002042 contentEntry->fContent.writeText(" ");
2043 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2044 contentEntry->fContent.writeText(" Tf\n");
2045 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002046 }
2047}
2048
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002049int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002050 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2051 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002052 int resourceIndex = fFontResources.find(newFont.get());
2053 if (resourceIndex < 0) {
2054 resourceIndex = fFontResources.count();
2055 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002056 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002057 }
2058 return resourceIndex;
2059}
2060
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002061void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002062 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002063 const SkRegion& origClipRegion,
2064 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002065 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002066 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002067 SkMatrix matrix = origMatrix;
2068 SkRegion perspectiveBounds;
2069 const SkRegion* clipRegion = &origClipRegion;
2070 SkBitmap perspectiveBitmap;
2071 const SkBitmap* bitmap = &origBitmap;
2072 SkBitmap tmpSubsetBitmap;
2073
2074 // Rasterize the bitmap using perspective in a new bitmap.
2075 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002076 if (fRasterDpi == 0) {
2077 return;
2078 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002079 SkBitmap* subsetBitmap;
2080 if (srcRect) {
2081 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2082 return;
2083 }
2084 subsetBitmap = &tmpSubsetBitmap;
2085 } else {
2086 subsetBitmap = &tmpSubsetBitmap;
2087 *subsetBitmap = origBitmap;
2088 }
2089 srcRect = NULL;
2090
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002091 // Transform the bitmap in the new space, without taking into
2092 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002093 SkPath perspectiveOutline;
2094 perspectiveOutline.addRect(
2095 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2096 SkIntToScalar(subsetBitmap->height())));
2097 perspectiveOutline.transform(origMatrix);
2098
2099 // TODO(edisonn): perf - use current clip too.
2100 // Retrieve the bounds of the new shape.
2101 SkRect bounds = perspectiveOutline.getBounds();
2102
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002103 // Transform the bitmap in the new space, taking into
2104 // account the initial transform.
2105 SkMatrix total = origMatrix;
2106 total.postConcat(fInitialTransform);
2107 total.postScale(SkIntToScalar(fRasterDpi) /
2108 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2109 SkIntToScalar(fRasterDpi) /
2110 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2111 SkPath physicalPerspectiveOutline;
2112 physicalPerspectiveOutline.addRect(
2113 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2114 SkIntToScalar(subsetBitmap->height())));
2115 physicalPerspectiveOutline.transform(total);
2116
2117 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2118 bounds.width();
2119 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2120 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002121
2122 // TODO(edisonn): A better approach would be to use a bitmap shader
2123 // (in clamp mode) and draw a rect over the entire bounding box. Then
2124 // intersect perspectiveOutline to the clip. That will avoid introducing
2125 // alpha to the image while still giving good behavior at the edge of
2126 // the image. Avoiding alpha will reduce the pdf size and generation
2127 // CPU time some.
2128
reed@google.com9ebcac52014-01-24 18:53:42 +00002129 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2130 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002131 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002132 return;
2133 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002134 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2135
reed89443ab2014-06-27 11:34:19 -07002136 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002137
2138 SkScalar deltaX = bounds.left();
2139 SkScalar deltaY = bounds.top();
2140
2141 SkMatrix offsetMatrix = origMatrix;
2142 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002143 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002144
2145 // Translate the draw in the new canvas, so we perfectly fit the
2146 // shape in the bitmap.
2147 canvas.setMatrix(offsetMatrix);
2148
2149 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2150
2151 // Make sure the final bits are in the bitmap.
2152 canvas.flush();
2153
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002154 // In the new space, we use the identity matrix translated
2155 // and scaled to reflect DPI.
2156 matrix.setScale(1 / scaleX, 1 / scaleY);
2157 matrix.postTranslate(deltaX, deltaY);
2158
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002159 perspectiveBounds.setRect(
2160 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2161 SkScalarFloorToInt(bounds.y()),
2162 SkScalarCeilToInt(bounds.width()),
2163 SkScalarCeilToInt(bounds.height())));
2164 clipRegion = &perspectiveBounds;
2165 srcRect = NULL;
2166 bitmap = &perspectiveBitmap;
2167 }
2168
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002169 SkMatrix scaled;
2170 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002171 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2172 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002173 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002174 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002175 scaled.postScale(SkIntToScalar(subset.width()),
2176 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002177 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002178 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002179 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2180 return;
2181 }
2182 if (content.needShape()) {
2183 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002184 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2185 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002186 shape.transform(matrix);
2187 content.setShape(shape);
2188 }
2189 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002190 return;
2191 }
2192
halcanarydaefa5b2014-08-27 13:00:54 -07002193 SkAutoTUnref<SkPDFObject> image(
2194 SkPDFCreateImageObject(*bitmap, subset, fEncoder));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002195 if (!image) {
2196 return;
2197 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002198
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002199 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002200 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002201}
reed@google.com982cb872011-12-07 18:34:08 +00002202