blob: 77aa7a353ce74ff5b0562238842751f94f2a22ce [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"
30#include "SkString.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000031#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000032#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000033#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000034#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000035
djsollen@google.com5df5e612013-10-03 14:42:24 +000036#ifdef SK_BUILD_FOR_ANDROID
37#include "SkTypeface_android.h"
38
39struct TypefaceFallbackData {
40 SkTypeface* typeface;
41 int lowerBounds;
42 int upperBounds;
43
44 bool operator==(const TypefaceFallbackData& b) const {
45 return typeface == b.typeface &&
46 lowerBounds == b.lowerBounds &&
47 upperBounds == b.upperBounds;
48 }
49};
50#endif
51
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000052// Utility functions
53
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000054static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000055 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
56 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000057 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000058 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
59 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000060 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000061 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
62 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000063 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000064 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
65 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000066}
67
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000068static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000069 SkPaint result = paint;
70 if (result.isFakeBoldText()) {
71 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
72 kStdFakeBoldInterpKeys,
73 kStdFakeBoldInterpValues,
74 kStdFakeBoldInterpLength);
75 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000076 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000077 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000078 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000079 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000080 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000081 result.setStrokeWidth(width);
82 }
83 return result;
84}
85
86// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000087static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000088 const uint16_t* glyphs, size_t len,
89 SkScalar* x, SkScalar* y) {
90 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000091 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000092 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000093
94 SkMatrix ident;
95 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000096 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000097 SkGlyphCache* cache = autoCache.getCache();
98
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000099 const char* start = reinterpret_cast<const char*>(glyphs);
100 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000101 SkFixed xAdv = 0, yAdv = 0;
102
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000103 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000104 while (start < stop) {
105 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
106 xAdv += glyph.fAdvanceX;
107 yAdv += glyph.fAdvanceY;
108 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000109 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000110 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000111 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000112
113 SkScalar xAdj = SkFixedToScalar(xAdv);
114 SkScalar yAdj = SkFixedToScalar(yAdv);
115 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
116 xAdj = SkScalarHalf(xAdj);
117 yAdj = SkScalarHalf(yAdj);
118 }
119 *x = *x - xAdj;
120 *y = *y - yAdj;
121}
122
reed@google.comfed86bd2013-03-14 15:04:57 +0000123static size_t max_glyphid_for_typeface(SkTypeface* typeface) {
124 SkAutoResolveDefaultTypeface autoResolve(typeface);
125 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000126 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000127}
128
129typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
130
131static size_t force_glyph_encoding(const SkPaint& paint, const void* text,
132 size_t len, SkGlyphStorage* storage,
133 uint16_t** glyphIDs) {
134 // Make sure we have a glyph id encoding.
135 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
136 size_t numGlyphs = paint.textToGlyphs(text, len, NULL);
137 storage->reset(numGlyphs);
138 paint.textToGlyphs(text, len, storage->get());
139 *glyphIDs = storage->get();
140 return numGlyphs;
141 }
142
143 // For user supplied glyph ids we need to validate them.
144 SkASSERT((len & 1) == 0);
145 size_t numGlyphs = len / 2;
146 const uint16_t* input =
147 reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
148
149 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
150 size_t validated;
151 for (validated = 0; validated < numGlyphs; ++validated) {
152 if (input[validated] > maxGlyphID) {
153 break;
154 }
155 }
156 if (validated >= numGlyphs) {
157 *glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
158 return numGlyphs;
159 }
160
161 // Silently drop anything out of range.
162 storage->reset(numGlyphs);
163 if (validated > 0) {
164 memcpy(storage->get(), input, validated * sizeof(uint16_t));
165 }
166
167 for (size_t i = validated; i < numGlyphs; ++i) {
168 storage->get()[i] = input[i];
169 if (input[i] > maxGlyphID) {
170 storage->get()[i] = 0;
171 }
172 }
173 *glyphIDs = storage->get();
174 return numGlyphs;
175}
176
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000177static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
178 SkWStream* content) {
179 // Flip the text about the x-axis to account for origin swap and include
180 // the passed parameters.
181 content->writeText("1 0 ");
182 SkPDFScalar::Append(0 - textSkewX, content);
183 content->writeText(" -1 ");
184 SkPDFScalar::Append(x, content);
185 content->writeText(" ");
186 SkPDFScalar::Append(y, content);
187 content->writeText(" Tm\n");
188}
189
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000190// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
191// later being our representation of an object in the PDF file.
192struct GraphicStateEntry {
193 GraphicStateEntry();
194
195 // Compare the fields we care about when setting up a new content entry.
196 bool compareInitialState(const GraphicStateEntry& b);
197
198 SkMatrix fMatrix;
199 // We can't do set operations on Paths, though PDF natively supports
200 // intersect. If the clip stack does anything other than intersect,
201 // we have to fall back to the region. Treat fClipStack as authoritative.
202 // See http://code.google.com/p/skia/issues/detail?id=221
203 SkClipStack fClipStack;
204 SkRegion fClipRegion;
205
206 // When emitting the content entry, we will ensure the graphic state
207 // is set to these values first.
208 SkColor fColor;
209 SkScalar fTextScaleX; // Zero means we don't care what the value is.
210 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
211 int fShaderIndex;
212 int fGraphicStateIndex;
213
214 // We may change the font (i.e. for Type1 support) within a
215 // ContentEntry. This is the one currently in effect, or NULL if none.
216 SkPDFFont* fFont;
217 // In PDF, text size has no default value. It is only valid if fFont is
218 // not NULL.
219 SkScalar fTextSize;
220};
221
222GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
223 fTextScaleX(SK_Scalar1),
224 fTextFill(SkPaint::kFill_Style),
225 fShaderIndex(-1),
226 fGraphicStateIndex(-1),
227 fFont(NULL),
228 fTextSize(SK_ScalarNaN) {
229 fMatrix.reset();
230}
231
232bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& b) {
233 return fColor == b.fColor &&
234 fShaderIndex == b.fShaderIndex &&
235 fGraphicStateIndex == b.fGraphicStateIndex &&
236 fMatrix == b.fMatrix &&
237 fClipStack == b.fClipStack &&
238 (fTextScaleX == 0 ||
239 b.fTextScaleX == 0 ||
240 (fTextScaleX == b.fTextScaleX && fTextFill == b.fTextFill));
241}
242
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000243class GraphicStackState {
244public:
245 GraphicStackState(const SkClipStack& existingClipStack,
246 const SkRegion& existingClipRegion,
247 SkWStream* contentStream)
248 : fStackDepth(0),
249 fContentStream(contentStream) {
250 fEntries[0].fClipStack = existingClipStack;
251 fEntries[0].fClipRegion = existingClipRegion;
252 }
253
254 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000255 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000256 void updateMatrix(const SkMatrix& matrix);
257 void updateDrawingState(const GraphicStateEntry& state);
258
259 void drainStack();
260
261private:
262 void push();
263 void pop();
264 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
265
266 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
267 static const int kMaxStackDepth = 12;
268 GraphicStateEntry fEntries[kMaxStackDepth + 1];
269 int fStackDepth;
270 SkWStream* fContentStream;
271};
272
273void GraphicStackState::drainStack() {
274 while (fStackDepth) {
275 pop();
276 }
277}
278
279void GraphicStackState::push() {
280 SkASSERT(fStackDepth < kMaxStackDepth);
281 fContentStream->writeText("q\n");
282 fStackDepth++;
283 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
284}
285
286void GraphicStackState::pop() {
287 SkASSERT(fStackDepth > 0);
288 fContentStream->writeText("Q\n");
289 fStackDepth--;
290}
291
robertphillips@google.com80214e22012-07-20 15:33:18 +0000292// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000293// and then skips over the leading entries as specified in prefix. It requires
294// and asserts that "prefix" will be a prefix to "stack."
295static void skip_clip_stack_prefix(const SkClipStack& prefix,
296 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000297 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000298 SkClipStack::B2TIter prefixIter(prefix);
299 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000300
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000301 const SkClipStack::Element* prefixEntry;
302 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000303
304 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000305 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000306 iterEntry = iter->next();
307 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000308 // Because of SkClipStack does internal intersection, the last clip
309 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000310 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000311 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
312 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
313 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000314 // back up the iterator by one
315 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000316 prefixEntry = prefixIter.next();
317 break;
318 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000319 }
320
321 SkASSERT(prefixEntry == NULL);
322}
323
324static void emit_clip(SkPath* clipPath, SkRect* clipRect,
325 SkWStream* contentStream) {
326 SkASSERT(clipPath || clipRect);
327
328 SkPath::FillType clipFill;
329 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000330 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000331 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000332 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000333 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
334 clipFill = SkPath::kWinding_FillType;
335 }
336
337 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
338 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
339 if (clipFill == SkPath::kEvenOdd_FillType) {
340 contentStream->writeText("W* n\n");
341 } else {
342 contentStream->writeText("W n\n");
343 }
344}
345
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000346#ifdef SK_PDF_USE_PATHOPS
347/* Calculate an inverted path's equivalent non-inverted path, given the
348 * canvas bounds.
349 * outPath may alias with invPath (since this is supported by PathOps).
350 */
351static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
352 SkPath* outPath) {
353 SkASSERT(invPath.isInverseFillType());
354
355 SkPath clipPath;
356 clipPath.addRect(bounds);
357
358 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
359}
360
361// Sanity check the numerical values of the SkRegion ops and PathOps ops
362// enums so region_op_to_pathops_op can do a straight passthrough cast.
363// If these are failing, it may be necessary to make region_op_to_pathops_op
364// do more.
365SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
366 region_pathop_mismatch);
367SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
368 region_pathop_mismatch);
369SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
370 region_pathop_mismatch);
371SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
372 region_pathop_mismatch);
373SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
374 (int)kReverseDifference_PathOp,
375 region_pathop_mismatch);
376
377static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
378 SkASSERT(op >= 0);
379 SkASSERT(op <= SkRegion::kReverseDifference_Op);
380 return (SkPathOp)op;
381}
382
383/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
384 * Returns true if successful, or false if not successful.
385 * If successful, the resulting clip is stored in outClipPath.
386 * If not successful, outClipPath is undefined, and a fallback method
387 * should be used.
388 */
389static bool get_clip_stack_path(const SkMatrix& transform,
390 const SkClipStack& clipStack,
391 const SkRegion& clipRegion,
392 SkPath* outClipPath) {
393 outClipPath->reset();
394 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
395
396 const SkClipStack::Element* clipEntry;
397 SkClipStack::Iter iter;
398 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
399 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
400 SkPath entryPath;
401 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
402 outClipPath->reset();
403 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
404 continue;
405 } else if (SkClipStack::Element::kRect_Type == clipEntry->getType()) {
406 entryPath.addRect(clipEntry->getRect());
407 } else if (SkClipStack::Element::kPath_Type == clipEntry->getType()) {
408 entryPath = clipEntry->getPath();
409 }
410 entryPath.transform(transform);
411
412 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
413 *outClipPath = entryPath;
414 } else {
415 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
416 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
417 return false;
418 }
419 }
420 }
421
422 if (outClipPath->isInverseFillType()) {
423 // The bounds are slightly outset to ensure this is correct in the
424 // face of floating-point accuracy and possible SkRegion bitmap
425 // approximations.
426 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
427 clipBounds.outset(SK_Scalar1, SK_Scalar1);
428 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
429 return false;
430 }
431 }
432 return true;
433}
434#endif
435
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000436// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000437// graphic state stack, and the fact that we can know all the clips used
438// on the page to optimize this.
439void GraphicStackState::updateClip(const SkClipStack& clipStack,
440 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000441 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000442 if (clipStack == currentEntry()->fClipStack) {
443 return;
444 }
445
446 while (fStackDepth > 0) {
447 pop();
448 if (clipStack == currentEntry()->fClipStack) {
449 return;
450 }
451 }
452 push();
453
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000454 currentEntry()->fClipStack = clipStack;
455 currentEntry()->fClipRegion = clipRegion;
456
457 SkMatrix transform;
458 transform.setTranslate(translation.fX, translation.fY);
459
460#ifdef SK_PDF_USE_PATHOPS
461 SkPath clipPath;
462 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
463 emit_clip(&clipPath, NULL, fContentStream);
464 return;
465 }
466#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000467 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
468 // already been applied. (If this is a top level device, then it specifies
469 // a clip to the content area. If this is a layer, then it specifies
470 // the clip in effect when the layer was created.) There's no need to
471 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
472 // initial clip on the parent layer. (This means there's a bug if the user
473 // expands the clip and then uses any xfer mode that uses dst:
474 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000475 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000476 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
477
478 // If the clip stack does anything other than intersect or if it uses
479 // an inverse fill type, we have to fall back to the clip region.
480 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000481 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000482 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000483 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
484 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000485 needRegion = true;
486 break;
487 }
488 }
489
490 if (needRegion) {
491 SkPath clipPath;
492 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
493 emit_clip(&clipPath, NULL, fContentStream);
494 } else {
495 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000496 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000497 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000498 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
499 switch (clipEntry->getType()) {
500 case SkClipStack::Element::kRect_Type: {
501 SkRect translatedClip;
502 transform.mapRect(&translatedClip, clipEntry->getRect());
503 emit_clip(NULL, &translatedClip, fContentStream);
504 break;
505 }
506 case SkClipStack::Element::kPath_Type: {
507 SkPath translatedPath;
508 clipEntry->getPath().transform(transform, &translatedPath);
509 emit_clip(&translatedPath, NULL, fContentStream);
510 break;
511 }
512 default:
513 SkASSERT(false);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000514 }
515 }
516 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000517}
518
519void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
520 if (matrix == currentEntry()->fMatrix) {
521 return;
522 }
523
524 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
525 SkASSERT(fStackDepth > 0);
526 SkASSERT(fEntries[fStackDepth].fClipStack ==
527 fEntries[fStackDepth -1].fClipStack);
528 pop();
529
530 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
531 }
532 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
533 return;
534 }
535
536 push();
537 SkPDFUtils::AppendTransform(matrix, fContentStream);
538 currentEntry()->fMatrix = matrix;
539}
540
541void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
542 // PDF treats a shader as a color, so we only set one or the other.
543 if (state.fShaderIndex >= 0) {
544 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000545 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000546 currentEntry()->fShaderIndex = state.fShaderIndex;
547 }
548 } else {
549 if (state.fColor != currentEntry()->fColor ||
550 currentEntry()->fShaderIndex >= 0) {
551 emit_pdf_color(state.fColor, fContentStream);
552 fContentStream->writeText("RG ");
553 emit_pdf_color(state.fColor, fContentStream);
554 fContentStream->writeText("rg\n");
555 currentEntry()->fColor = state.fColor;
556 currentEntry()->fShaderIndex = -1;
557 }
558 }
559
560 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000561 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000562 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
563 }
564
565 if (state.fTextScaleX) {
566 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
567 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
568 SkIntToScalar(100));
569 SkPDFScalar::Append(pdfScale, fContentStream);
570 fContentStream->writeText(" Tz\n");
571 currentEntry()->fTextScaleX = state.fTextScaleX;
572 }
573 if (state.fTextFill != currentEntry()->fTextFill) {
574 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
575 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
576 enum_must_match_value);
577 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
578 enum_must_match_value);
579 fContentStream->writeDecAsText(state.fTextFill);
580 fContentStream->writeText(" Tr\n");
581 currentEntry()->fTextFill = state.fTextFill;
582 }
583 }
584}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000585
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000586SkBaseDevice* SkPDFDevice::onCreateCompatibleDevice(SkBitmap::Config config,
587 int width, int height,
588 bool isOpaque,
589 Usage usage) {
bsalomon@google.come97f0852011-06-17 13:10:25 +0000590 SkMatrix initialTransform;
591 initialTransform.reset();
592 SkISize size = SkISize::Make(width, height);
593 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
594}
595
596
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000597struct ContentEntry {
598 GraphicStateEntry fState;
599 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000600 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000601
602 // If the stack is too deep we could get Stack Overflow.
603 // So we manually destruct the object.
604 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000605 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000606 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000607 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000608 // When the destructor is called, fNext is NULL and exits.
609 delete val;
610 val = valNext;
611 }
612 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000613};
614
615// A helper class to automatically finish a ContentEntry at the end of a
616// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000617class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000619 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
620 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000621 : fDevice(device),
622 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000623 fXfermode(SkXfermode::kSrcOver_Mode),
624 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000625 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
626 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000627 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
628 const SkRegion& clipRegion, const SkMatrix& matrix,
629 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000630 : fDevice(device),
631 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000632 fXfermode(SkXfermode::kSrcOver_Mode),
633 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000634 init(clipStack, clipRegion, matrix, paint, hasText);
635 }
636
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000637 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000638 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000639 SkPath* shape = &fShape;
640 if (shape->isEmpty()) {
641 shape = NULL;
642 }
643 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000644 }
reed@google.comfc641d02012-09-20 17:52:20 +0000645 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000646 }
647
648 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000649
650 /* Returns true when we explicitly need the shape of the drawing. */
651 bool needShape() {
652 switch (fXfermode) {
653 case SkXfermode::kClear_Mode:
654 case SkXfermode::kSrc_Mode:
655 case SkXfermode::kSrcIn_Mode:
656 case SkXfermode::kSrcOut_Mode:
657 case SkXfermode::kDstIn_Mode:
658 case SkXfermode::kDstOut_Mode:
659 case SkXfermode::kSrcATop_Mode:
660 case SkXfermode::kDstATop_Mode:
661 case SkXfermode::kModulate_Mode:
662 return true;
663 default:
664 return false;
665 }
666 }
667
668 /* Returns true unless we only need the shape of the drawing. */
669 bool needSource() {
670 if (fXfermode == SkXfermode::kClear_Mode) {
671 return false;
672 }
673 return true;
674 }
675
676 /* If the shape is different than the alpha component of the content, then
677 * setShape should be called with the shape. In particular, images and
678 * devices have rectangular shape.
679 */
680 void setShape(const SkPath& shape) {
681 fShape = shape;
682 }
683
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000684private:
685 SkPDFDevice* fDevice;
686 ContentEntry* fContentEntry;
687 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000688 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000689 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000690
691 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
692 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000693 // Shape has to be flatten before we get here.
694 if (matrix.hasPerspective()) {
695 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000696 return;
697 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000698 if (paint.getXfermode()) {
699 paint.getXfermode()->asMode(&fXfermode);
700 }
701 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
702 matrix, paint, hasText,
703 &fDstFormXObject);
704 }
705};
706
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000707////////////////////////////////////////////////////////////////////////////////
708
ctguil@chromium.org15261292011-04-29 17:54:16 +0000709static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000710 const SkMatrix* initialTransform) {
reed@android.comf2b98d62010-12-20 18:26:13 +0000711 SkBitmap bitmap;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000712 if (initialTransform) {
713 // Compute the size of the drawing area.
714 SkVector drawingSize;
715 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000716 drawingSize.set(SkIntToScalar(contentSize.fWidth),
717 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000718 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000719 // This shouldn't happen, initial transform should be invertible.
720 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000721 inverse.reset();
722 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000723 inverse.mapVectors(&drawingSize, 1);
724 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
725 bitmap.setConfig(SkBitmap::kNo_Config, abs(size.fWidth),
726 abs(size.fHeight));
727 } else {
728 bitmap.setConfig(SkBitmap::kNo_Config, abs(contentSize.fWidth),
729 abs(contentSize.fHeight));
730 }
731
reed@android.comf2b98d62010-12-20 18:26:13 +0000732 return bitmap;
733}
734
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000735// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000736SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000737 const SkMatrix& initialTransform)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000738 : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
ctguil@chromium.org15261292011-04-29 17:54:16 +0000739 fPageSize(pageSize),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000740 fContentSize(contentSize),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000741 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000742 fLastMarginContentEntry(NULL),
edisonn@google.comd9dfa182013-04-24 13:01:01 +0000743 fClipStack(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000744 fEncoder(NULL),
745 fRasterDpi(SkFloatToScalar(72.0f)) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000746 // Just report that PDF does not supports perspective in the
747 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000748 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
749
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000750 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000751 // origin at the bottom left. This matrix corrects for that. But that only
752 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000753 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
754 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000755 fInitialTransform.preConcat(initialTransform);
756
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000757 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000758 fExistingClipRegion.setRect(existingClip);
759
760 this->init();
761}
762
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000763// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000764SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
765 const SkClipStack& existingClipStack,
766 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000767 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000768 fPageSize(layerSize),
769 fContentSize(layerSize),
770 fExistingClipStack(existingClipStack),
771 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000772 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000773 fLastMarginContentEntry(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000774 fClipStack(NULL),
775 fEncoder(NULL),
776 fRasterDpi(SkFloatToScalar(72.0f)) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000777 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000778 this->init();
779}
780
781SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000782 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000783}
784
785void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000786 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000787 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000788 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000789 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000790 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000791 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000792 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000793 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000794 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
795 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000796}
797
vandebo@chromium.org98594282011-07-25 22:34:12 +0000798void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000799 fGraphicStateResources.unrefAll();
800 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000801 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000802 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000803 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000804 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000805 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000806
vandebo@chromium.org98594282011-07-25 22:34:12 +0000807 if (clearFontUsage) {
808 fFontGlyphUsage->reset();
809 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000810}
811
reed@google.com982cb872011-12-07 18:34:08 +0000812uint32_t SkPDFDevice::getDeviceCapabilities() {
813 return kVector_Capability;
814}
815
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000816void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000817 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000818 this->init();
819
820 SkPaint paint;
821 paint.setColor(color);
822 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000823 SkMatrix identity;
824 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000825 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
826 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000827 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000828}
829
830void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000831 SkPaint newPaint = paint;
832 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000833 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000834 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000835}
836
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000837void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
838 ContentEntry* contentEntry) {
839 if (!contentEntry) {
840 return;
841 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000842 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
843 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000844 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000845 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000846 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000847 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000848 inverse.mapRect(&bbox);
849
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000850 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000851 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000852 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000853}
854
855void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
856 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000857 const SkPaint& passedPaint) {
858 if (count == 0) {
859 return;
860 }
861
epoger@google.comb58772f2013-03-08 09:09:10 +0000862 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
863 return;
864 }
865
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000866 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
867 // We only use this when there's a path effect because of the overhead
868 // of multiple calls to setUpContentEntry it causes.
869 if (passedPaint.getPathEffect()) {
870 if (d.fClip->isEmpty()) {
871 return;
872 }
873 SkDraw pointDraw(d);
874 pointDraw.fDevice = this;
875 pointDraw.drawPoints(mode, count, points, passedPaint, true);
876 return;
877 }
878
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000879 const SkPaint* paint = &passedPaint;
880 SkPaint modifiedPaint;
881
882 if (mode == SkCanvas::kPoints_PointMode &&
883 paint->getStrokeCap() != SkPaint::kRound_Cap) {
884 modifiedPaint = *paint;
885 paint = &modifiedPaint;
886 if (paint->getStrokeWidth()) {
887 // PDF won't draw a single point with square/butt caps because the
888 // orientation is ambiguous. Draw a rectangle instead.
889 modifiedPaint.setStyle(SkPaint::kFill_Style);
890 SkScalar strokeWidth = paint->getStrokeWidth();
891 SkScalar halfStroke = SkScalarHalf(strokeWidth);
892 for (size_t i = 0; i < count; i++) {
893 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
894 r.inset(-halfStroke, -halfStroke);
895 drawRect(d, r, modifiedPaint);
896 }
897 return;
898 } else {
899 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
900 }
901 }
902
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000903 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000904 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000905 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000906 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000907
908 switch (mode) {
909 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000910 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000911 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000912 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000913 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000914 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000915 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000916 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000917 break;
918 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000919 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000920 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000921 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000922 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000923 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000924 &content.entry()->fContent);
925 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000926 }
927 break;
928 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000929 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
930 for (size_t i = 0; i < count; i++) {
931 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000932 &content.entry()->fContent);
933 SkPDFUtils::ClosePath(&content.entry()->fContent);
934 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000935 }
936 break;
937 default:
938 SkASSERT(false);
939 }
940}
941
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000942void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000943 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000944 SkRect r = rect;
945 r.sort();
946
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000947 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000948 if (d.fClip->isEmpty()) {
949 return;
950 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000951 SkPath path;
952 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000953 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000954 return;
955 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000956
epoger@google.comb58772f2013-03-08 09:09:10 +0000957 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000958 return;
959 }
960
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000961 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000962 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000963 return;
964 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000965 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000966 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000967 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000968}
969
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000970void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000971 const SkPaint& paint, const SkMatrix* prePathMatrix,
972 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000973 SkPath modifiedPath;
974 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
975
976 SkMatrix matrix = *d.fMatrix;
977 if (prePathMatrix) {
978 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
979 if (!pathIsMutable) {
980 pathPtr = &modifiedPath;
981 pathIsMutable = true;
982 }
983 origPath.transform(*prePathMatrix, pathPtr);
984 } else {
985 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000986 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000987 return;
988 }
989 }
990 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000991
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000992 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000993 if (d.fClip->isEmpty()) {
994 return;
995 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000996 if (!pathIsMutable) {
997 pathPtr = &modifiedPath;
998 pathIsMutable = true;
999 }
1000 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001001
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001002 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001003 noEffectPaint.setPathEffect(NULL);
1004 if (fill) {
1005 noEffectPaint.setStyle(SkPaint::kFill_Style);
1006 } else {
1007 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1008 noEffectPaint.setStrokeWidth(0);
1009 }
1010 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001011 return;
1012 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001013
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001014#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001015 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001016 return;
1017 }
1018#endif
1019
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001020 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001021 return;
1022 }
1023
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001024 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001025 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001026 return;
1027 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001028 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1029 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001030 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001031 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001032}
1033
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001034void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1035 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001036 const SkPaint& paint,
1037 SkCanvas::DrawBitmapRectFlags flags) {
1038 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001039 SkMatrix matrix;
1040 SkRect bitmapBounds, tmpSrc, tmpDst;
1041 SkBitmap tmpBitmap;
1042
1043 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1044
1045 // Compute matrix from the two rectangles
1046 if (src) {
1047 tmpSrc = *src;
1048 } else {
1049 tmpSrc = bitmapBounds;
1050 }
1051 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1052
1053 const SkBitmap* bitmapPtr = &bitmap;
1054
1055 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1056 // needed (if the src was clipped). No check needed if src==null.
1057 if (src) {
1058 if (!bitmapBounds.contains(*src)) {
1059 if (!tmpSrc.intersect(bitmapBounds)) {
1060 return; // nothing to draw
1061 }
1062 // recompute dst, based on the smaller tmpSrc
1063 matrix.mapRect(&tmpDst, tmpSrc);
1064 }
1065
1066 // since we may need to clamp to the borders of the src rect within
1067 // the bitmap, we extract a subset.
1068 // TODO: make sure this is handled in drawBitmap and remove from here.
1069 SkIRect srcIR;
1070 tmpSrc.roundOut(&srcIR);
1071 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1072 return;
1073 }
1074 bitmapPtr = &tmpBitmap;
1075
1076 // Since we did an extract, we need to adjust the matrix accordingly
1077 SkScalar dx = 0, dy = 0;
1078 if (srcIR.fLeft > 0) {
1079 dx = SkIntToScalar(srcIR.fLeft);
1080 }
1081 if (srcIR.fTop > 0) {
1082 dy = SkIntToScalar(srcIR.fTop);
1083 }
1084 if (dx || dy) {
1085 matrix.preTranslate(dx, dy);
1086 }
1087 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001088 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001089}
1090
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001091void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001092 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001093 if (d.fClip->isEmpty()) {
1094 return;
1095 }
1096
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001097 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001098 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001099 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1100 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001101}
1102
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001103void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001104 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001105 if (d.fClip->isEmpty()) {
1106 return;
1107 }
1108
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001109 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001110 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001111 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1112 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001113}
1114
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001115void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001116 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001117 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1118 if (paint.getMaskFilter() != NULL) {
1119 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1120 // making text unreadable (e.g. same text twice when using CSS shadows).
1121 return;
1122 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001123 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001124 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001125 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001126 return;
1127 }
1128
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001129 SkGlyphStorage storage(0);
1130 uint16_t* glyphIDs = NULL;
1131 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1132 &glyphIDs);
1133 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001134
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001135 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001136 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001137 content.entry()->fContent.writeText("BT\n");
1138 set_text_transform(x, y, textPaint.getTextSkewX(),
1139 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001140 size_t consumedGlyphCount = 0;
1141 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001142 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1143 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001144 size_t availableGlyphs =
1145 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1146 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001147 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1148 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001149 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001150 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001151 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001152 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001153 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001154 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001155 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001156 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001157}
1158
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001159void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001160 const SkScalar pos[], SkScalar constY,
1161 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001162 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1163 if (paint.getMaskFilter() != NULL) {
1164 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1165 // making text unreadable (e.g. same text twice when using CSS shadows).
1166 return;
1167 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001168 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001169 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001170 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001171 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001172 return;
1173 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001174
djsollen@google.com5df5e612013-10-03 14:42:24 +00001175#ifdef SK_BUILD_FOR_ANDROID
1176 /*
1177 * In the case that we have enabled fallback fonts on Android we need to
1178 * take the following steps to ensure that the PDF draws all characters,
1179 * regardless of their underlying font file, correctly.
1180 *
1181 * 1. Convert input into GlyphID encoding if it currently is not
1182 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1183 * glyph resolves to
1184 * 3. Iterate over those typefaces and recursively call this function with
1185 * only the glyphs (and their positions) that the typeface is capable of
1186 * resolving.
1187 */
1188 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1189 uint16_t* glyphIDs = NULL;
1190 SkGlyphStorage tmpStorage(0);
1191 size_t numGlyphs = 0;
1192
1193 // convert to glyphIDs
1194 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1195 numGlyphs = len / 2;
1196 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1197 } else {
1198 numGlyphs = paint.textToGlyphs(text, len, NULL);
1199 tmpStorage.reset(numGlyphs);
1200 paint.textToGlyphs(text, len, tmpStorage.get());
1201 glyphIDs = tmpStorage.get();
1202 }
1203
1204 // if no typeface is provided in the paint get the default
1205 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1206 if (NULL == origFace.get()) {
1207 origFace.reset(SkTypeface::RefDefault());
1208 }
1209 const uint16_t origGlyphCount = origFace->countGlyphs();
1210
1211 // keep a list of the already visited typefaces and some data about them
1212 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1213
1214 // find all the typefaces needed to resolve this run of text
1215 bool usesOriginalTypeface = false;
1216 for (uint16_t x = 0; x < numGlyphs; ++x) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001217 // optimization that checks to see if original typeface can resolve
1218 // the glyph
djsollen@google.com5df5e612013-10-03 14:42:24 +00001219 if (glyphIDs[x] < origGlyphCount) {
1220 usesOriginalTypeface = true;
1221 continue;
1222 }
1223
1224 // find the fallback typeface that supports this glyph
1225 TypefaceFallbackData data;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001226 data.typeface =
1227 SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1228 paint.getPaintOptionsAndroid(),
1229 &data.lowerBounds,
1230 &data.upperBounds);
djsollen@google.com5df5e612013-10-03 14:42:24 +00001231 // add the typeface and its data if we don't have it
1232 if (data.typeface && !visitedTypefaces.contains(data)) {
1233 visitedTypefaces.push(data);
1234 }
1235 }
1236
1237 // if the original font was used then add it to the list as well
1238 if (usesOriginalTypeface) {
1239 TypefaceFallbackData* data = visitedTypefaces.push();
1240 data->typeface = origFace.get();
1241 data->lowerBounds = 0;
1242 data->upperBounds = origGlyphCount;
1243 }
1244
1245 // keep a scratch glyph and pos storage
1246 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1247 SkScalar* tmpPos = posStorage.get();
1248 SkGlyphStorage glyphStorage(numGlyphs);
1249 uint16_t* tmpGlyphIDs = glyphStorage.get();
1250
1251 // loop through all the valid typefaces, trim the glyphs to only those
1252 // resolved by the typeface, and then draw that run of glyphs
1253 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1254 const TypefaceFallbackData& data = visitedTypefaces[x];
1255
1256 int tmpGlyphCount = 0;
1257 for (uint16_t y = 0; y < numGlyphs; ++y) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001258 if (glyphIDs[y] >= data.lowerBounds &&
1259 glyphIDs[y] < data.upperBounds) {
djsollen@google.com5df5e612013-10-03 14:42:24 +00001260 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1261 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1262 &(pos[y * scalarsPerPos]),
1263 scalarsPerPos * sizeof(SkScalar));
1264 tmpGlyphCount++;
1265 }
1266 }
1267
1268 // recursively call this function with the right typeface
1269 SkPaint tmpPaint = paint;
1270 tmpPaint.setTypeface(data.typeface);
1271 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1272
1273 // turn off fallback chaining
1274 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1275 paintOpts.setUseFontFallbacks(false);
1276 tmpPaint.setPaintOptionsAndroid(paintOpts);
1277
1278 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1279 scalarsPerPos, tmpPaint);
1280 }
1281 return;
1282 }
1283#endif
1284
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001285 SkGlyphStorage storage(0);
1286 uint16_t* glyphIDs = NULL;
1287 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1288 &glyphIDs);
1289 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001290
1291 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001292 content.entry()->fContent.writeText("BT\n");
1293 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001294 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001295 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001296 uint16_t encodedValue = glyphIDs[i];
1297 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001298 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001299 i--;
1300 continue;
1301 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001302 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001303 SkScalar x = pos[i * scalarsPerPos];
1304 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001305 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001306 set_text_transform(x, y, textPaint.getTextSkewX(),
1307 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001308 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001309 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001310 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001311 content.entry()->fContent.writeText(encodedString.c_str());
1312 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001313 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001314 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001315}
1316
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001317void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001318 const SkPath& path, const SkMatrix* matrix,
1319 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001320 if (d.fClip->isEmpty()) {
1321 return;
1322 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001323 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001324}
1325
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001326void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001327 int vertexCount, const SkPoint verts[],
1328 const SkPoint texs[], const SkColor colors[],
1329 SkXfermode* xmode, const uint16_t indices[],
1330 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001331 if (d.fClip->isEmpty()) {
1332 return;
1333 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001334 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001335}
1336
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001337void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1338 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001339 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1340 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001341 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001342 return;
1343 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001344
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001345 // Assume that a vector capable device means that it's a PDF Device.
1346 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001347 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001348 return;
1349 }
1350
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001351 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001352 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001353 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001354 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001355 return;
1356 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001357 if (content.needShape()) {
1358 SkPath shape;
1359 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001360 SkIntToScalar(device->width()),
1361 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001362 content.setShape(shape);
1363 }
1364 if (!content.needSource()) {
1365 return;
1366 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001367
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001368 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1369 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001370 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001371
1372 // Merge glyph sets from the drawn device.
1373 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001374}
1375
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001376void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1377 INHERITED::onAttachToCanvas(canvas);
1378
1379 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1380 fClipStack = canvas->getClipStack();
1381}
1382
1383void SkPDFDevice::onDetachFromCanvas() {
1384 INHERITED::onDetachFromCanvas();
1385
1386 fClipStack = NULL;
1387}
1388
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001389ContentEntry* SkPDFDevice::getLastContentEntry() {
1390 if (fDrawingArea == kContent_DrawingArea) {
1391 return fLastContentEntry;
1392 } else {
1393 return fLastMarginContentEntry;
1394 }
1395}
1396
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001397SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001398 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001399 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001400 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001401 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001402 }
1403}
1404
1405void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1406 if (fDrawingArea == kContent_DrawingArea) {
1407 fLastContentEntry = contentEntry;
1408 } else {
1409 fLastMarginContentEntry = contentEntry;
1410 }
1411}
1412
1413void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001414 // A ScopedContentEntry only exists during the course of a draw call, so
1415 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001416 fDrawingArea = drawingArea;
1417}
1418
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001419SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001420 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001421 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001422
1423 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001424 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001425 fResourceDict->insertResourceAsReference(
1426 SkPDFResourceDict::kExtGState_ResourceType,
1427 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001428 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001429 }
1430
1431 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001432 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001433 fResourceDict->insertResourceAsReference(
1434 SkPDFResourceDict::kXObject_ResourceType,
1435 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001436 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001437 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001438
1439 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001440 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001441 fResourceDict->insertResourceAsReference(
1442 SkPDFResourceDict::kFont_ResourceType,
1443 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001444 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001445 }
1446
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001447 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001448 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001449 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001450 fResourceDict->insertResourceAsReference(
1451 SkPDFResourceDict::kPattern_ResourceType,
1452 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001453 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001454 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001455 }
1456 return fResourceDict;
1457}
1458
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001459const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1460 return fFontResources;
1461}
1462
reed@google.com2a006c12012-09-19 17:05:55 +00001463SkPDFArray* SkPDFDevice::copyMediaBox() const {
1464 // should this be a singleton?
1465 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001466
reed@google.com2a006c12012-09-19 17:05:55 +00001467 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001468 mediaBox->reserve(4);
1469 mediaBox->append(zero.get());
1470 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001471 mediaBox->appendInt(fPageSize.fWidth);
1472 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001473 return mediaBox;
1474}
1475
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001476SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001477 SkMemoryStream* result = new SkMemoryStream;
1478 result->setData(this->copyContentToData())->unref();
1479 return result;
1480}
1481
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001482void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1483 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001484 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1485 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001486 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001487 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001488 SkPoint translation;
1489 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001490 translation.negate();
1491 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1492 translation);
1493 gsState.updateMatrix(entry->fState.fMatrix);
1494 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001495
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001496 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001497 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001498 entry = entry->fNext.get();
1499 }
1500 gsState.drainStack();
1501}
1502
reed@google.com5667afc2011-06-27 14:42:15 +00001503SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001504 SkDynamicMemoryWStream data;
1505 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1506 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001507 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001508
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001509 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1510 // colors the contentArea white before it starts drawing into it and
1511 // that currently acts as our clip.
1512 // Also, think about adding a transform here (or assume that the values
1513 // sent across account for that)
1514 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001515
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001516 // If the content area is the entire page, then we don't need to clip
1517 // the content area (PDF area clips to the page size). Otherwise,
1518 // we have to clip to the content area; we've already applied the
1519 // initial transform, so just clip to the device size.
1520 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001521 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1522 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001523 emit_clip(NULL, &r, &data);
1524 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001525
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001526 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001527
reed@google.com5667afc2011-06-27 14:42:15 +00001528 // potentially we could cache this SkData, and only rebuild it if we
1529 // see that our state has changed.
1530 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001531}
1532
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001533#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001534/* Draws an inverse filled path by using Path Ops to compute the positive
1535 * inverse using the current clip as the inverse bounds.
1536 * Return true if this was an inverse path and was properly handled,
1537 * otherwise returns false and the normal drawing routine should continue,
1538 * either as a (incorrect) fallback or because the path was not inverse
1539 * in the first place.
1540 */
1541bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001542 const SkPaint& paint, bool pathIsMutable,
1543 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001544 if (!origPath.isInverseFillType()) {
1545 return false;
1546 }
1547
1548 if (d.fClip->isEmpty()) {
1549 return false;
1550 }
1551
1552 SkPath modifiedPath;
1553 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1554 SkPaint noInversePaint(paint);
1555
1556 // Merge stroking operations into final path.
1557 if (SkPaint::kStroke_Style == paint.getStyle() ||
1558 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1559 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1560 if (doFillPath) {
1561 noInversePaint.setStyle(SkPaint::kFill_Style);
1562 noInversePaint.setStrokeWidth(0);
1563 pathPtr = &modifiedPath;
1564 } else {
1565 // To be consistent with the raster output, hairline strokes
1566 // are rendered as non-inverted.
1567 modifiedPath.toggleInverseFillType();
1568 drawPath(d, modifiedPath, paint, NULL, true);
1569 return true;
1570 }
1571 }
1572
1573 // Get bounds of clip in current transform space
1574 // (clip bounds are given in device space).
1575 SkRect bounds;
1576 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001577 SkMatrix totalMatrix = *d.fMatrix;
1578 if (prePathMatrix) {
1579 totalMatrix.preConcat(*prePathMatrix);
1580 }
1581 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001582 return false;
1583 }
1584 bounds.set(d.fClip->getBounds());
1585 transformInverse.mapRect(&bounds);
1586
1587 // Extend the bounds by the line width (plus some padding)
1588 // so the edge doesn't cause a visible stroke.
1589 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1590 paint.getStrokeWidth() + SK_Scalar1);
1591
1592 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1593 return false;
1594 }
1595
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001596 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001597 return true;
1598}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001599#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001600
epoger@google.comb58772f2013-03-08 09:09:10 +00001601bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1602 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001603 SkAnnotation* annotationInfo = p.getAnnotation();
1604 if (!annotationInfo) {
1605 return false;
1606 }
1607 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001608 if (urlData) {
1609 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001610 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001611 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001612 SkData* linkToName = annotationInfo->find(
1613 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001614 if (linkToName) {
1615 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001616 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001617 }
1618 return false;
1619}
1620
1621bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1622 const SkMatrix& matrix,
1623 const SkPaint& paint) {
1624 SkAnnotation* annotationInfo = paint.getAnnotation();
1625 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001626 return false;
1627 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001628 SkData* nameData = annotationInfo->find(
1629 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001630 if (nameData) {
1631 for (size_t i = 0; i < count; i++) {
1632 defineNamedDestination(nameData, points[i], matrix);
1633 }
reed@google.com44699382013-10-31 17:28:30 +00001634 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001635 }
1636 return false;
1637}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001638
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001639SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1640 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001641 SkMatrix transform = matrix;
1642 transform.postConcat(fInitialTransform);
1643 SkRect translatedRect;
1644 transform.mapRect(&translatedRect, r);
1645
reed@google.com2a006c12012-09-19 17:05:55 +00001646 if (NULL == fAnnotations) {
1647 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001648 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001649 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001650 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001651 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001652
epoger@google.comb58772f2013-03-08 09:09:10 +00001653 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001654 border->reserve(3);
1655 border->appendInt(0); // Horizontal corner radius.
1656 border->appendInt(0); // Vertical corner radius.
1657 border->appendInt(0); // Width, 0 = no border.
1658 annotation->insert("Border", border.get());
1659
epoger@google.comb58772f2013-03-08 09:09:10 +00001660 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001661 rect->reserve(4);
1662 rect->appendScalar(translatedRect.fLeft);
1663 rect->appendScalar(translatedRect.fTop);
1664 rect->appendScalar(translatedRect.fRight);
1665 rect->appendScalar(translatedRect.fBottom);
1666 annotation->insert("Rect", rect.get());
1667
epoger@google.comb58772f2013-03-08 09:09:10 +00001668 return annotation;
1669}
epoger@google.com1cad8982013-03-06 00:05:13 +00001670
epoger@google.comb58772f2013-03-08 09:09:10 +00001671void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1672 const SkMatrix& matrix) {
1673 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1674
1675 SkString url(static_cast<const char *>(urlData->data()),
1676 urlData->size() - 1);
1677 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1678 action->insertName("S", "URI");
1679 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1680 annotation->insert("A", action.get());
1681}
1682
1683void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1684 const SkMatrix& matrix) {
1685 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1686 SkString name(static_cast<const char *>(nameData->data()),
1687 nameData->size() - 1);
1688 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1689}
1690
1691struct NamedDestination {
1692 const SkData* nameData;
1693 SkPoint point;
1694
1695 NamedDestination(const SkData* nameData, const SkPoint& point)
1696 : nameData(nameData), point(point) {
1697 nameData->ref();
1698 }
1699
1700 ~NamedDestination() {
1701 nameData->unref();
1702 }
1703};
1704
1705void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1706 const SkMatrix& matrix) {
1707 SkMatrix transform = matrix;
1708 transform.postConcat(fInitialTransform);
1709 SkPoint translatedPoint;
1710 transform.mapXY(point.x(), point.y(), &translatedPoint);
1711 fNamedDestinations.push(
1712 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1713}
1714
1715void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1716 int nDest = fNamedDestinations.count();
1717 for (int i = 0; i < nDest; i++) {
1718 NamedDestination* dest = fNamedDestinations[i];
1719 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1720 pdfDest->reserve(5);
1721 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1722 pdfDest->appendName("XYZ");
1723 pdfDest->appendScalar(dest->point.x());
1724 pdfDest->appendScalar(dest->point.y());
1725 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001726 dict->insert(static_cast<const char *>(dest->nameData->data()),
1727 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001728 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001729}
1730
reed@google.comfc641d02012-09-20 17:52:20 +00001731SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1732 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001733 // We always draw the form xobjects that we create back into the device, so
1734 // we simply preserve the font usage instead of pulling it out and merging
1735 // it back in later.
1736 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001737 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001738 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001739}
1740
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001741void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1742 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001743 const SkClipStack* clipStack,
1744 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001745 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001746 bool invertClip) {
1747 if (clipRegion.isEmpty() && !invertClip) {
1748 return;
1749 }
1750
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001751 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1752 SkPDFGraphicState::GetSMaskGraphicState(
1753 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1754
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001755 SkMatrix identity;
1756 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001757 SkPaint paint;
1758 paint.setXfermodeMode(mode);
1759 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001760 if (!content.entry()) {
1761 return;
1762 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001763 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001764 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001765 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001766
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001767 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001768 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001769 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001770}
1771
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001772ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1773 const SkRegion& clipRegion,
1774 const SkMatrix& matrix,
1775 const SkPaint& paint,
1776 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001777 SkPDFFormXObject** dst) {
1778 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001779 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001780 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001781 }
1782
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001783 // The clip stack can come from an SkDraw where it is technically optional.
1784 SkClipStack synthesizedClipStack;
1785 if (clipStack == NULL) {
1786 if (clipRegion == fExistingClipRegion) {
1787 clipStack = &fExistingClipStack;
1788 } else {
1789 // GraphicStackState::updateClip expects the clip stack to have
1790 // fExistingClip as a prefix, so start there, then set the clip
1791 // to the passed region.
1792 synthesizedClipStack = fExistingClipStack;
1793 SkPath clipPath;
1794 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001795 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1796 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001797 clipStack = &synthesizedClipStack;
1798 }
1799 }
1800
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001801 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1802 if (paint.getXfermode()) {
1803 paint.getXfermode()->asMode(&xfermode);
1804 }
1805
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001806 // For the following modes, we want to handle source and destination
1807 // separately, so make an object of what's already there.
1808 if (xfermode == SkXfermode::kClear_Mode ||
1809 xfermode == SkXfermode::kSrc_Mode ||
1810 xfermode == SkXfermode::kSrcIn_Mode ||
1811 xfermode == SkXfermode::kDstIn_Mode ||
1812 xfermode == SkXfermode::kSrcOut_Mode ||
1813 xfermode == SkXfermode::kDstOut_Mode ||
1814 xfermode == SkXfermode::kSrcATop_Mode ||
1815 xfermode == SkXfermode::kDstATop_Mode ||
1816 xfermode == SkXfermode::kModulate_Mode) {
1817 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001818 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001819 SkASSERT(isContentEmpty());
1820 } else if (xfermode != SkXfermode::kSrc_Mode &&
1821 xfermode != SkXfermode::kSrcOut_Mode) {
1822 // Except for Src and SrcOut, if there isn't anything already there,
1823 // then we're done.
1824 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001825 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001826 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001827 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001828 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001829
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001830 // Dst xfer mode doesn't draw source at all.
1831 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001832 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001833 }
1834
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001835 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001836 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001837
1838 ContentEntry* lastContentEntry = getLastContentEntry();
1839 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1840 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001841 } else {
1842 newEntry.reset(new ContentEntry);
1843 entry = newEntry.get();
1844 }
1845
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001846 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001847 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001848 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1849 entry->fState.compareInitialState(lastContentEntry->fState)) {
1850 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001851 }
1852
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001853 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001854 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001855 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001856 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001857 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001858 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001859 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001860 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001861 lastContentEntry->fNext.reset(entry);
1862 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001863 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001864 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001865 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001866}
1867
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001868void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001869 SkPDFFormXObject* dst,
1870 SkPath* shape) {
1871 if (xfermode != SkXfermode::kClear_Mode &&
1872 xfermode != SkXfermode::kSrc_Mode &&
1873 xfermode != SkXfermode::kSrcIn_Mode &&
1874 xfermode != SkXfermode::kDstIn_Mode &&
1875 xfermode != SkXfermode::kSrcOut_Mode &&
1876 xfermode != SkXfermode::kDstOut_Mode &&
1877 xfermode != SkXfermode::kSrcATop_Mode &&
1878 xfermode != SkXfermode::kDstATop_Mode &&
1879 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001880 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001881 return;
1882 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001883 if (!dst) {
1884 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1885 xfermode == SkXfermode::kSrcOut_Mode);
1886 return;
1887 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001888
1889 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001890 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001891 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001892 // We have to make a copy of these here because changing the current
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001893 // content into a form-xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001894 SkClipStack clipStack = contentEntries->fState.fClipStack;
1895 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001896
reed@google.comfc641d02012-09-20 17:52:20 +00001897 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001898 if (isContentEmpty()) {
1899 SkASSERT(xfermode == SkXfermode::kClear_Mode);
1900 } else {
1901 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001902 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001903 }
1904
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001905 SkMatrix identity;
1906 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001907
1908 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1909 // without alpha.
1910 if (xfermode == SkXfermode::kSrcATop_Mode) {
1911 // TODO(vandebo): In order to properly support SrcATop we have to track
1912 // the shape of what's been drawn at all times. It's the intersection of
1913 // the non-transparent parts of the device and the outlines (shape) of
1914 // all images and devices drawn.
1915 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1916 &clipStack, clipRegion,
1917 SkXfermode::kSrcOver_Mode, true);
1918 } else {
1919 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1920 SkPDFFormXObject* dstMask = srcFormXObject.get();
1921 if (shape != NULL) {
1922 // Draw shape into a form-xobject.
1923 SkDraw d;
1924 d.fMatrix = &identity;
1925 d.fClip = &clipRegion;
1926 d.fClipStack = &clipStack;
1927 SkPaint filledPaint;
1928 filledPaint.setColor(SK_ColorBLACK);
1929 filledPaint.setStyle(SkPaint::kFill_Style);
1930 this->drawPath(d, *shape, filledPaint, NULL, true);
1931
1932 dstMaskStorage.reset(createFormXObjectFromDevice());
1933 dstMask = dstMaskStorage.get();
1934 }
1935 drawFormXObjectWithMask(addXObjectResource(dst), dstMask, &clipStack,
1936 clipRegion, SkXfermode::kSrcOver_Mode, true);
1937 }
1938
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001939 SkPaint stockPaint;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001940
1941 if (xfermode == SkXfermode::kClear_Mode) {
1942 return;
1943 } else if (xfermode == SkXfermode::kSrc_Mode ||
1944 xfermode == SkXfermode::kDstATop_Mode) {
1945 ScopedContentEntry content(this, &clipStack, clipRegion, identity,
1946 stockPaint);
1947 if (content.entry()) {
1948 SkPDFUtils::DrawFormXObject(
1949 this->addXObjectResource(srcFormXObject.get()),
1950 &content.entry()->fContent);
1951 }
1952 if (xfermode == SkXfermode::kSrc_Mode) {
1953 return;
1954 }
1955 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
1956 ScopedContentEntry content(this, &clipStack, clipRegion, identity,
1957 stockPaint);
1958 if (content.entry()) {
1959 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1960 &content.entry()->fContent);
1961 }
1962 }
1963
1964 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1965 xfermode == SkXfermode::kDstIn_Mode ||
1966 xfermode == SkXfermode::kSrcOut_Mode ||
1967 xfermode == SkXfermode::kDstOut_Mode ||
1968 xfermode == SkXfermode::kSrcATop_Mode ||
1969 xfermode == SkXfermode::kDstATop_Mode ||
1970 xfermode == SkXfermode::kModulate_Mode);
1971
1972 ScopedContentEntry inShapeContentEntry(this, &fExistingClipStack,
1973 fExistingClipRegion, identity,
1974 stockPaint);
1975 if (!inShapeContentEntry.entry()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001976 return;
1977 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001978
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001979 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001980 xfermode == SkXfermode::kSrcOut_Mode ||
1981 xfermode == SkXfermode::kSrcATop_Mode) {
1982 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1983 &clipStack, clipRegion,
1984 SkXfermode::kSrcOver_Mode,
1985 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001986 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001987 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1988 if (xfermode == SkXfermode::kModulate_Mode) {
1989 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1990 dst, &clipStack, clipRegion,
1991 SkXfermode::kSrcOver_Mode, false);
1992 mode = SkXfermode::kMultiply_Mode;
1993 }
1994 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
1995 &clipStack, clipRegion, mode,
1996 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001997 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001998}
1999
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002000bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002001 ContentEntry* contentEntries = getContentEntries()->get();
2002 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
2003 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002004 return true;
2005 }
2006 return false;
2007}
2008
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002009void SkPDFDevice::populateGraphicStateEntryFromPaint(
2010 const SkMatrix& matrix,
2011 const SkClipStack& clipStack,
2012 const SkRegion& clipRegion,
2013 const SkPaint& paint,
2014 bool hasText,
2015 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002016 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002017
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002018 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
2019 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002020
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002021 entry->fMatrix = matrix;
2022 entry->fClipStack = clipStack;
2023 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002024 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2025 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002026
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002027 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002028 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002029 const SkShader* shader = paint.getShader();
2030 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002031 if (shader) {
2032 // PDF positions patterns relative to the initial transform, so
2033 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002034 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00002035 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002036
2037 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002038 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002039 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00002040
2041 // We need to apply the initial transform to bounds in order to get
2042 // bounds in a consistent coordinate system.
2043 SkRect boundsTemp;
2044 boundsTemp.set(bounds);
2045 fInitialTransform.mapRect(&boundsTemp);
2046 boundsTemp.roundOut(&bounds);
2047
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002048 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002049
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002050 if (pdfShader.get()) {
2051 // pdfShader has been canonicalized so we can directly compare
2052 // pointers.
2053 int resourceIndex = fShaderResources.find(pdfShader.get());
2054 if (resourceIndex < 0) {
2055 resourceIndex = fShaderResources.count();
2056 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002057 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002058 }
2059 entry->fShaderIndex = resourceIndex;
2060 } else {
2061 // A color shader is treated as an invalid shader so we don't have
2062 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002063 SkShader::GradientInfo gradientInfo;
2064 SkColor gradientColor;
2065 gradientInfo.fColors = &gradientColor;
2066 gradientInfo.fColorOffsets = NULL;
2067 gradientInfo.fColorCount = 1;
2068 if (shader->asAGradient(&gradientInfo) ==
2069 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002070 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2071 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002072 }
2073 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002074 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002075
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002076 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002077 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002078 newGraphicState.reset(
2079 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002080 } else {
2081 SkPaint newPaint = paint;
2082 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002083 newGraphicState.reset(
2084 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002085 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002086 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002087 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002088
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002089 if (hasText) {
2090 entry->fTextScaleX = paint.getTextScaleX();
2091 entry->fTextFill = paint.getStyle();
2092 } else {
2093 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002094 }
2095}
2096
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002097int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2098 // Assumes that gs has been canonicalized (so we can directly compare
2099 // pointers).
2100 int result = fGraphicStateResources.find(gs);
2101 if (result < 0) {
2102 result = fGraphicStateResources.count();
2103 fGraphicStateResources.push(gs);
2104 gs->ref();
2105 }
2106 return result;
2107}
2108
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002109int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2110 // Assumes that xobject has been canonicalized (so we can directly compare
2111 // pointers).
2112 int result = fXObjectResources.find(xObject);
2113 if (result < 0) {
2114 result = fXObjectResources.count();
2115 fXObjectResources.push(xObject);
2116 xObject->ref();
2117 }
2118 return result;
2119}
2120
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002121void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2122 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002123 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002124 if (contentEntry->fState.fFont == NULL ||
2125 contentEntry->fState.fTextSize != paint.getTextSize() ||
2126 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002127 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002128 contentEntry->fContent.writeText("/");
2129 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2130 SkPDFResourceDict::kFont_ResourceType,
2131 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002132 contentEntry->fContent.writeText(" ");
2133 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2134 contentEntry->fContent.writeText(" Tf\n");
2135 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002136 }
2137}
2138
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002139int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002140 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2141 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002142 int resourceIndex = fFontResources.find(newFont.get());
2143 if (resourceIndex < 0) {
2144 resourceIndex = fFontResources.count();
2145 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002146 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002147 }
2148 return resourceIndex;
2149}
2150
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002151void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002152 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002153 const SkRegion& origClipRegion,
2154 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002155 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002156 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002157 SkMatrix matrix = origMatrix;
2158 SkRegion perspectiveBounds;
2159 const SkRegion* clipRegion = &origClipRegion;
2160 SkBitmap perspectiveBitmap;
2161 const SkBitmap* bitmap = &origBitmap;
2162 SkBitmap tmpSubsetBitmap;
2163
2164 // Rasterize the bitmap using perspective in a new bitmap.
2165 if (origMatrix.hasPerspective()) {
2166 SkBitmap* subsetBitmap;
2167 if (srcRect) {
2168 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2169 return;
2170 }
2171 subsetBitmap = &tmpSubsetBitmap;
2172 } else {
2173 subsetBitmap = &tmpSubsetBitmap;
2174 *subsetBitmap = origBitmap;
2175 }
2176 srcRect = NULL;
2177
2178 // Transform the bitmap in the new space.
2179 SkPath perspectiveOutline;
2180 perspectiveOutline.addRect(
2181 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2182 SkIntToScalar(subsetBitmap->height())));
2183 perspectiveOutline.transform(origMatrix);
2184
2185 // TODO(edisonn): perf - use current clip too.
2186 // Retrieve the bounds of the new shape.
2187 SkRect bounds = perspectiveOutline.getBounds();
2188
2189 // TODO(edisonn): add DPI settings. Currently 1 pixel/point, which does
2190 // not look great, but it is not producing large PDFs.
2191
2192 // TODO(edisonn): A better approach would be to use a bitmap shader
2193 // (in clamp mode) and draw a rect over the entire bounding box. Then
2194 // intersect perspectiveOutline to the clip. That will avoid introducing
2195 // alpha to the image while still giving good behavior at the edge of
2196 // the image. Avoiding alpha will reduce the pdf size and generation
2197 // CPU time some.
2198
2199 perspectiveBitmap.setConfig(SkBitmap::kARGB_8888_Config,
2200 SkScalarCeilToInt(bounds.width()),
2201 SkScalarCeilToInt(bounds.height()));
2202 perspectiveBitmap.allocPixels();
2203 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2204
2205 SkBitmapDevice device(perspectiveBitmap);
2206 SkCanvas canvas(&device);
2207
2208 SkScalar deltaX = bounds.left();
2209 SkScalar deltaY = bounds.top();
2210
2211 SkMatrix offsetMatrix = origMatrix;
2212 offsetMatrix.postTranslate(-deltaX, -deltaY);
2213
2214 // Translate the draw in the new canvas, so we perfectly fit the
2215 // shape in the bitmap.
2216 canvas.setMatrix(offsetMatrix);
2217
2218 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2219
2220 // Make sure the final bits are in the bitmap.
2221 canvas.flush();
2222
2223 // In the new space, we use the identity matrix translated.
2224 matrix.setTranslate(deltaX, deltaY);
2225 perspectiveBounds.setRect(
2226 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2227 SkScalarFloorToInt(bounds.y()),
2228 SkScalarCeilToInt(bounds.width()),
2229 SkScalarCeilToInt(bounds.height())));
2230 clipRegion = &perspectiveBounds;
2231 srcRect = NULL;
2232 bitmap = &perspectiveBitmap;
2233 }
2234
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002235 SkMatrix scaled;
2236 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002237 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2238 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002239 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002240 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002241 scaled.postScale(SkIntToScalar(subset.width()),
2242 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002243 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002244 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002245 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2246 return;
2247 }
2248 if (content.needShape()) {
2249 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002250 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2251 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002252 shape.transform(matrix);
2253 content.setShape(shape);
2254 }
2255 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002256 return;
2257 }
2258
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002259 SkAutoTUnref<SkPDFImage> image(
2260 SkPDFImage::CreateImage(*bitmap, subset, fEncoder));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002261 if (!image) {
2262 return;
2263 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002264
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002265 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002266 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002267}
reed@google.com982cb872011-12-07 18:34:08 +00002268
2269bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2270 SkCanvas::Config8888) {
2271 return false;
2272}
reed@google.comb55deeb2012-01-06 14:43:09 +00002273
2274bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2275 return false;
2276}