blob: ff7dd2cd9252475e46eed12a4c8d623a07f4eb68 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000015#include "SkFontHost.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000016#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000018#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
23#include "SkPDFImage.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000024#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000026#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000029#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000030#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000031#include "SkString.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000032#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000033#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000034#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000035#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000036
djsollen@google.com5df5e612013-10-03 14:42:24 +000037#ifdef SK_BUILD_FOR_ANDROID
38#include "SkTypeface_android.h"
39
40struct TypefaceFallbackData {
41 SkTypeface* typeface;
42 int lowerBounds;
43 int upperBounds;
44
45 bool operator==(const TypefaceFallbackData& b) const {
46 return typeface == b.typeface &&
47 lowerBounds == b.lowerBounds &&
48 upperBounds == b.upperBounds;
49 }
50};
51#endif
52
edisonn@google.com73a7ea32013-11-11 20:55:15 +000053#define DPI_FOR_RASTER_SCALE_ONE 72
54
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000055// Utility functions
56
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000057static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000058 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
59 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000060 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000061 SkScalarDiv(SkIntToScalar(SkColorGetR(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(SkColorGetG(color)), colorMax), result);
65 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000066 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000067 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
68 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000069}
70
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000071static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000072 SkPaint result = paint;
73 if (result.isFakeBoldText()) {
74 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
75 kStdFakeBoldInterpKeys,
76 kStdFakeBoldInterpValues,
77 kStdFakeBoldInterpLength);
78 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000079 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000081 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000082 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000083 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000084 result.setStrokeWidth(width);
85 }
86 return result;
87}
88
89// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000090static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000091 const uint16_t* glyphs, size_t len,
92 SkScalar* x, SkScalar* y) {
93 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000094 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000095 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000096
97 SkMatrix ident;
98 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000099 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000100 SkGlyphCache* cache = autoCache.getCache();
101
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000102 const char* start = reinterpret_cast<const char*>(glyphs);
103 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000104 SkFixed xAdv = 0, yAdv = 0;
105
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000106 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000107 while (start < stop) {
108 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
109 xAdv += glyph.fAdvanceX;
110 yAdv += glyph.fAdvanceY;
111 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000112 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000113 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000114 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000115
116 SkScalar xAdj = SkFixedToScalar(xAdv);
117 SkScalar yAdj = SkFixedToScalar(yAdv);
118 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
119 xAdj = SkScalarHalf(xAdj);
120 yAdj = SkScalarHalf(yAdj);
121 }
122 *x = *x - xAdj;
123 *y = *y - yAdj;
124}
125
reed@google.comfed86bd2013-03-14 15:04:57 +0000126static size_t max_glyphid_for_typeface(SkTypeface* typeface) {
127 SkAutoResolveDefaultTypeface autoResolve(typeface);
128 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000129 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000130}
131
132typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
133
134static size_t force_glyph_encoding(const SkPaint& paint, const void* text,
135 size_t len, SkGlyphStorage* storage,
136 uint16_t** glyphIDs) {
137 // Make sure we have a glyph id encoding.
138 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
139 size_t numGlyphs = paint.textToGlyphs(text, len, NULL);
140 storage->reset(numGlyphs);
141 paint.textToGlyphs(text, len, storage->get());
142 *glyphIDs = storage->get();
143 return numGlyphs;
144 }
145
146 // For user supplied glyph ids we need to validate them.
147 SkASSERT((len & 1) == 0);
148 size_t numGlyphs = len / 2;
149 const uint16_t* input =
150 reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
151
152 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
153 size_t validated;
154 for (validated = 0; validated < numGlyphs; ++validated) {
155 if (input[validated] > maxGlyphID) {
156 break;
157 }
158 }
159 if (validated >= numGlyphs) {
160 *glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
161 return numGlyphs;
162 }
163
164 // Silently drop anything out of range.
165 storage->reset(numGlyphs);
166 if (validated > 0) {
167 memcpy(storage->get(), input, validated * sizeof(uint16_t));
168 }
169
170 for (size_t i = validated; i < numGlyphs; ++i) {
171 storage->get()[i] = input[i];
172 if (input[i] > maxGlyphID) {
173 storage->get()[i] = 0;
174 }
175 }
176 *glyphIDs = storage->get();
177 return numGlyphs;
178}
179
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000180static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
181 SkWStream* content) {
182 // Flip the text about the x-axis to account for origin swap and include
183 // the passed parameters.
184 content->writeText("1 0 ");
185 SkPDFScalar::Append(0 - textSkewX, content);
186 content->writeText(" -1 ");
187 SkPDFScalar::Append(x, content);
188 content->writeText(" ");
189 SkPDFScalar::Append(y, content);
190 content->writeText(" Tm\n");
191}
192
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000193// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
194// later being our representation of an object in the PDF file.
195struct GraphicStateEntry {
196 GraphicStateEntry();
197
198 // Compare the fields we care about when setting up a new content entry.
199 bool compareInitialState(const GraphicStateEntry& b);
200
201 SkMatrix fMatrix;
202 // We can't do set operations on Paths, though PDF natively supports
203 // intersect. If the clip stack does anything other than intersect,
204 // we have to fall back to the region. Treat fClipStack as authoritative.
205 // See http://code.google.com/p/skia/issues/detail?id=221
206 SkClipStack fClipStack;
207 SkRegion fClipRegion;
208
209 // When emitting the content entry, we will ensure the graphic state
210 // is set to these values first.
211 SkColor fColor;
212 SkScalar fTextScaleX; // Zero means we don't care what the value is.
213 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
214 int fShaderIndex;
215 int fGraphicStateIndex;
216
217 // We may change the font (i.e. for Type1 support) within a
218 // ContentEntry. This is the one currently in effect, or NULL if none.
219 SkPDFFont* fFont;
220 // In PDF, text size has no default value. It is only valid if fFont is
221 // not NULL.
222 SkScalar fTextSize;
223};
224
225GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
226 fTextScaleX(SK_Scalar1),
227 fTextFill(SkPaint::kFill_Style),
228 fShaderIndex(-1),
229 fGraphicStateIndex(-1),
230 fFont(NULL),
231 fTextSize(SK_ScalarNaN) {
232 fMatrix.reset();
233}
234
235bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& b) {
236 return fColor == b.fColor &&
237 fShaderIndex == b.fShaderIndex &&
238 fGraphicStateIndex == b.fGraphicStateIndex &&
239 fMatrix == b.fMatrix &&
240 fClipStack == b.fClipStack &&
241 (fTextScaleX == 0 ||
242 b.fTextScaleX == 0 ||
243 (fTextScaleX == b.fTextScaleX && fTextFill == b.fTextFill));
244}
245
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000246class GraphicStackState {
247public:
248 GraphicStackState(const SkClipStack& existingClipStack,
249 const SkRegion& existingClipRegion,
250 SkWStream* contentStream)
251 : fStackDepth(0),
252 fContentStream(contentStream) {
253 fEntries[0].fClipStack = existingClipStack;
254 fEntries[0].fClipRegion = existingClipRegion;
255 }
256
257 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000258 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000259 void updateMatrix(const SkMatrix& matrix);
260 void updateDrawingState(const GraphicStateEntry& state);
261
262 void drainStack();
263
264private:
265 void push();
266 void pop();
267 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
268
269 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
270 static const int kMaxStackDepth = 12;
271 GraphicStateEntry fEntries[kMaxStackDepth + 1];
272 int fStackDepth;
273 SkWStream* fContentStream;
274};
275
276void GraphicStackState::drainStack() {
277 while (fStackDepth) {
278 pop();
279 }
280}
281
282void GraphicStackState::push() {
283 SkASSERT(fStackDepth < kMaxStackDepth);
284 fContentStream->writeText("q\n");
285 fStackDepth++;
286 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
287}
288
289void GraphicStackState::pop() {
290 SkASSERT(fStackDepth > 0);
291 fContentStream->writeText("Q\n");
292 fStackDepth--;
293}
294
robertphillips@google.com80214e22012-07-20 15:33:18 +0000295// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000296// and then skips over the leading entries as specified in prefix. It requires
297// and asserts that "prefix" will be a prefix to "stack."
298static void skip_clip_stack_prefix(const SkClipStack& prefix,
299 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000300 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000301 SkClipStack::B2TIter prefixIter(prefix);
302 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000303
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000304 const SkClipStack::Element* prefixEntry;
305 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000306
307 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000308 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000309 iterEntry = iter->next();
310 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000311 // Because of SkClipStack does internal intersection, the last clip
312 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000313 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000314 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
315 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
316 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000317 // back up the iterator by one
318 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000319 prefixEntry = prefixIter.next();
320 break;
321 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000322 }
323
324 SkASSERT(prefixEntry == NULL);
325}
326
327static void emit_clip(SkPath* clipPath, SkRect* clipRect,
328 SkWStream* contentStream) {
329 SkASSERT(clipPath || clipRect);
330
331 SkPath::FillType clipFill;
332 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000333 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000334 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000335 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000336 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
337 clipFill = SkPath::kWinding_FillType;
338 }
339
340 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
341 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
342 if (clipFill == SkPath::kEvenOdd_FillType) {
343 contentStream->writeText("W* n\n");
344 } else {
345 contentStream->writeText("W n\n");
346 }
347}
348
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000349#ifdef SK_PDF_USE_PATHOPS
350/* Calculate an inverted path's equivalent non-inverted path, given the
351 * canvas bounds.
352 * outPath may alias with invPath (since this is supported by PathOps).
353 */
354static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
355 SkPath* outPath) {
356 SkASSERT(invPath.isInverseFillType());
357
358 SkPath clipPath;
359 clipPath.addRect(bounds);
360
361 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
362}
363
364// Sanity check the numerical values of the SkRegion ops and PathOps ops
365// enums so region_op_to_pathops_op can do a straight passthrough cast.
366// If these are failing, it may be necessary to make region_op_to_pathops_op
367// do more.
368SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
369 region_pathop_mismatch);
370SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
371 region_pathop_mismatch);
372SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
373 region_pathop_mismatch);
374SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
375 region_pathop_mismatch);
376SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
377 (int)kReverseDifference_PathOp,
378 region_pathop_mismatch);
379
380static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
381 SkASSERT(op >= 0);
382 SkASSERT(op <= SkRegion::kReverseDifference_Op);
383 return (SkPathOp)op;
384}
385
386/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
387 * Returns true if successful, or false if not successful.
388 * If successful, the resulting clip is stored in outClipPath.
389 * If not successful, outClipPath is undefined, and a fallback method
390 * should be used.
391 */
392static bool get_clip_stack_path(const SkMatrix& transform,
393 const SkClipStack& clipStack,
394 const SkRegion& clipRegion,
395 SkPath* outClipPath) {
396 outClipPath->reset();
397 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
398
399 const SkClipStack::Element* clipEntry;
400 SkClipStack::Iter iter;
401 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
402 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
403 SkPath entryPath;
404 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
405 outClipPath->reset();
406 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
407 continue;
408 } else if (SkClipStack::Element::kRect_Type == clipEntry->getType()) {
409 entryPath.addRect(clipEntry->getRect());
410 } else if (SkClipStack::Element::kPath_Type == clipEntry->getType()) {
411 entryPath = clipEntry->getPath();
412 }
413 entryPath.transform(transform);
414
415 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
416 *outClipPath = entryPath;
417 } else {
418 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
419 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
420 return false;
421 }
422 }
423 }
424
425 if (outClipPath->isInverseFillType()) {
426 // The bounds are slightly outset to ensure this is correct in the
427 // face of floating-point accuracy and possible SkRegion bitmap
428 // approximations.
429 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
430 clipBounds.outset(SK_Scalar1, SK_Scalar1);
431 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
432 return false;
433 }
434 }
435 return true;
436}
437#endif
438
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000439// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000440// graphic state stack, and the fact that we can know all the clips used
441// on the page to optimize this.
442void GraphicStackState::updateClip(const SkClipStack& clipStack,
443 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000444 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000445 if (clipStack == currentEntry()->fClipStack) {
446 return;
447 }
448
449 while (fStackDepth > 0) {
450 pop();
451 if (clipStack == currentEntry()->fClipStack) {
452 return;
453 }
454 }
455 push();
456
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000457 currentEntry()->fClipStack = clipStack;
458 currentEntry()->fClipRegion = clipRegion;
459
460 SkMatrix transform;
461 transform.setTranslate(translation.fX, translation.fY);
462
463#ifdef SK_PDF_USE_PATHOPS
464 SkPath clipPath;
465 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
466 emit_clip(&clipPath, NULL, fContentStream);
467 return;
468 }
469#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000470 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
471 // already been applied. (If this is a top level device, then it specifies
472 // a clip to the content area. If this is a layer, then it specifies
473 // the clip in effect when the layer was created.) There's no need to
474 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
475 // initial clip on the parent layer. (This means there's a bug if the user
476 // expands the clip and then uses any xfer mode that uses dst:
477 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000478 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000479 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
480
481 // If the clip stack does anything other than intersect or if it uses
482 // an inverse fill type, we have to fall back to the clip region.
483 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000484 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000485 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000486 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
487 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000488 needRegion = true;
489 break;
490 }
491 }
492
493 if (needRegion) {
494 SkPath clipPath;
495 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
496 emit_clip(&clipPath, NULL, fContentStream);
497 } else {
498 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000499 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000500 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000501 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
502 switch (clipEntry->getType()) {
503 case SkClipStack::Element::kRect_Type: {
504 SkRect translatedClip;
505 transform.mapRect(&translatedClip, clipEntry->getRect());
506 emit_clip(NULL, &translatedClip, fContentStream);
507 break;
508 }
509 case SkClipStack::Element::kPath_Type: {
510 SkPath translatedPath;
511 clipEntry->getPath().transform(transform, &translatedPath);
512 emit_clip(&translatedPath, NULL, fContentStream);
513 break;
514 }
515 default:
516 SkASSERT(false);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000517 }
518 }
519 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000520}
521
522void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
523 if (matrix == currentEntry()->fMatrix) {
524 return;
525 }
526
527 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
528 SkASSERT(fStackDepth > 0);
529 SkASSERT(fEntries[fStackDepth].fClipStack ==
530 fEntries[fStackDepth -1].fClipStack);
531 pop();
532
533 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
534 }
535 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
536 return;
537 }
538
539 push();
540 SkPDFUtils::AppendTransform(matrix, fContentStream);
541 currentEntry()->fMatrix = matrix;
542}
543
544void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
545 // PDF treats a shader as a color, so we only set one or the other.
546 if (state.fShaderIndex >= 0) {
547 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000548 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000549 currentEntry()->fShaderIndex = state.fShaderIndex;
550 }
551 } else {
552 if (state.fColor != currentEntry()->fColor ||
553 currentEntry()->fShaderIndex >= 0) {
554 emit_pdf_color(state.fColor, fContentStream);
555 fContentStream->writeText("RG ");
556 emit_pdf_color(state.fColor, fContentStream);
557 fContentStream->writeText("rg\n");
558 currentEntry()->fColor = state.fColor;
559 currentEntry()->fShaderIndex = -1;
560 }
561 }
562
563 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000564 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000565 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
566 }
567
568 if (state.fTextScaleX) {
569 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
570 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
571 SkIntToScalar(100));
572 SkPDFScalar::Append(pdfScale, fContentStream);
573 fContentStream->writeText(" Tz\n");
574 currentEntry()->fTextScaleX = state.fTextScaleX;
575 }
576 if (state.fTextFill != currentEntry()->fTextFill) {
577 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
578 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
579 enum_must_match_value);
580 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
581 enum_must_match_value);
582 fContentStream->writeDecAsText(state.fTextFill);
583 fContentStream->writeText(" Tr\n");
584 currentEntry()->fTextFill = state.fTextFill;
585 }
586 }
587}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000588
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000589SkBaseDevice* SkPDFDevice::onCreateCompatibleDevice(SkBitmap::Config config,
590 int width, int height,
591 bool isOpaque,
592 Usage usage) {
bsalomon@google.come97f0852011-06-17 13:10:25 +0000593 SkMatrix initialTransform;
594 initialTransform.reset();
595 SkISize size = SkISize::Make(width, height);
596 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
597}
598
599
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000600struct ContentEntry {
601 GraphicStateEntry fState;
602 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000603 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000604
605 // If the stack is too deep we could get Stack Overflow.
606 // So we manually destruct the object.
607 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000608 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000609 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000610 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000611 // When the destructor is called, fNext is NULL and exits.
612 delete val;
613 val = valNext;
614 }
615 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000616};
617
618// A helper class to automatically finish a ContentEntry at the end of a
619// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000620class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000621public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000622 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
623 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000624 : fDevice(device),
625 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000626 fXfermode(SkXfermode::kSrcOver_Mode),
627 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000628 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
629 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000630 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
631 const SkRegion& clipRegion, const SkMatrix& matrix,
632 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000633 : fDevice(device),
634 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000635 fXfermode(SkXfermode::kSrcOver_Mode),
636 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000637 init(clipStack, clipRegion, matrix, paint, hasText);
638 }
639
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000640 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000641 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000642 SkPath* shape = &fShape;
643 if (shape->isEmpty()) {
644 shape = NULL;
645 }
646 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000647 }
reed@google.comfc641d02012-09-20 17:52:20 +0000648 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000649 }
650
651 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000652
653 /* Returns true when we explicitly need the shape of the drawing. */
654 bool needShape() {
655 switch (fXfermode) {
656 case SkXfermode::kClear_Mode:
657 case SkXfermode::kSrc_Mode:
658 case SkXfermode::kSrcIn_Mode:
659 case SkXfermode::kSrcOut_Mode:
660 case SkXfermode::kDstIn_Mode:
661 case SkXfermode::kDstOut_Mode:
662 case SkXfermode::kSrcATop_Mode:
663 case SkXfermode::kDstATop_Mode:
664 case SkXfermode::kModulate_Mode:
665 return true;
666 default:
667 return false;
668 }
669 }
670
671 /* Returns true unless we only need the shape of the drawing. */
672 bool needSource() {
673 if (fXfermode == SkXfermode::kClear_Mode) {
674 return false;
675 }
676 return true;
677 }
678
679 /* If the shape is different than the alpha component of the content, then
680 * setShape should be called with the shape. In particular, images and
681 * devices have rectangular shape.
682 */
683 void setShape(const SkPath& shape) {
684 fShape = shape;
685 }
686
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000687private:
688 SkPDFDevice* fDevice;
689 ContentEntry* fContentEntry;
690 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000691 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000692 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000693
694 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
695 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000696 // Shape has to be flatten before we get here.
697 if (matrix.hasPerspective()) {
698 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000699 return;
700 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000701 if (paint.getXfermode()) {
702 paint.getXfermode()->asMode(&fXfermode);
703 }
704 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
705 matrix, paint, hasText,
706 &fDstFormXObject);
707 }
708};
709
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000710////////////////////////////////////////////////////////////////////////////////
711
ctguil@chromium.org15261292011-04-29 17:54:16 +0000712static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000713 const SkMatrix* initialTransform) {
reed@android.comf2b98d62010-12-20 18:26:13 +0000714 SkBitmap bitmap;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000715 if (initialTransform) {
716 // Compute the size of the drawing area.
717 SkVector drawingSize;
718 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000719 drawingSize.set(SkIntToScalar(contentSize.fWidth),
720 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000721 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000722 // This shouldn't happen, initial transform should be invertible.
723 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000724 inverse.reset();
725 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000726 inverse.mapVectors(&drawingSize, 1);
727 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
728 bitmap.setConfig(SkBitmap::kNo_Config, abs(size.fWidth),
729 abs(size.fHeight));
730 } else {
731 bitmap.setConfig(SkBitmap::kNo_Config, abs(contentSize.fWidth),
732 abs(contentSize.fHeight));
733 }
734
reed@android.comf2b98d62010-12-20 18:26:13 +0000735 return bitmap;
736}
737
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000738// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000739SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000740 const SkMatrix& initialTransform)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000741 : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
ctguil@chromium.org15261292011-04-29 17:54:16 +0000742 fPageSize(pageSize),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000743 fContentSize(contentSize),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000744 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000745 fLastMarginContentEntry(NULL),
edisonn@google.comd9dfa182013-04-24 13:01:01 +0000746 fClipStack(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000747 fEncoder(NULL),
748 fRasterDpi(SkFloatToScalar(72.0f)) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000749 // Just report that PDF does not supports perspective in the
750 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000751 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
752
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000753 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000754 // origin at the bottom left. This matrix corrects for that. But that only
755 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000756 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
757 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000758 fInitialTransform.preConcat(initialTransform);
759
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000760 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000761 fExistingClipRegion.setRect(existingClip);
762
763 this->init();
764}
765
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000766// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000767SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
768 const SkClipStack& existingClipStack,
769 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000770 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000771 fPageSize(layerSize),
772 fContentSize(layerSize),
773 fExistingClipStack(existingClipStack),
774 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000775 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000776 fLastMarginContentEntry(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000777 fClipStack(NULL),
778 fEncoder(NULL),
779 fRasterDpi(SkFloatToScalar(72.0f)) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000780 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000781 this->init();
782}
783
784SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000785 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000786}
787
788void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000789 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000790 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000791 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000792 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000793 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000794 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000795 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000796 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000797 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
798 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000799}
800
vandebo@chromium.org98594282011-07-25 22:34:12 +0000801void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000802 fGraphicStateResources.unrefAll();
803 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000804 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000805 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000806 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000807 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000808 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000809
vandebo@chromium.org98594282011-07-25 22:34:12 +0000810 if (clearFontUsage) {
811 fFontGlyphUsage->reset();
812 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000813}
814
reed@google.com982cb872011-12-07 18:34:08 +0000815uint32_t SkPDFDevice::getDeviceCapabilities() {
816 return kVector_Capability;
817}
818
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000819void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000820 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000821 this->init();
822
823 SkPaint paint;
824 paint.setColor(color);
825 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000826 SkMatrix identity;
827 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000828 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
829 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000830 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000831}
832
833void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000834 SkPaint newPaint = paint;
835 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000836 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000837 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000838}
839
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000840void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
841 ContentEntry* contentEntry) {
842 if (!contentEntry) {
843 return;
844 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000845 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
846 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000847 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000848 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000849 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000850 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000851 inverse.mapRect(&bbox);
852
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000853 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000854 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000855 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000856}
857
858void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
859 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000860 const SkPaint& passedPaint) {
861 if (count == 0) {
862 return;
863 }
864
epoger@google.comb58772f2013-03-08 09:09:10 +0000865 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
866 return;
867 }
868
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000869 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
870 // We only use this when there's a path effect because of the overhead
871 // of multiple calls to setUpContentEntry it causes.
872 if (passedPaint.getPathEffect()) {
873 if (d.fClip->isEmpty()) {
874 return;
875 }
876 SkDraw pointDraw(d);
877 pointDraw.fDevice = this;
878 pointDraw.drawPoints(mode, count, points, passedPaint, true);
879 return;
880 }
881
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000882 const SkPaint* paint = &passedPaint;
883 SkPaint modifiedPaint;
884
885 if (mode == SkCanvas::kPoints_PointMode &&
886 paint->getStrokeCap() != SkPaint::kRound_Cap) {
887 modifiedPaint = *paint;
888 paint = &modifiedPaint;
889 if (paint->getStrokeWidth()) {
890 // PDF won't draw a single point with square/butt caps because the
891 // orientation is ambiguous. Draw a rectangle instead.
892 modifiedPaint.setStyle(SkPaint::kFill_Style);
893 SkScalar strokeWidth = paint->getStrokeWidth();
894 SkScalar halfStroke = SkScalarHalf(strokeWidth);
895 for (size_t i = 0; i < count; i++) {
896 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
897 r.inset(-halfStroke, -halfStroke);
898 drawRect(d, r, modifiedPaint);
899 }
900 return;
901 } else {
902 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
903 }
904 }
905
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000906 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000907 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000908 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000909 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000910
911 switch (mode) {
912 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000913 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000914 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000915 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000916 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000917 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000918 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000919 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000920 break;
921 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000922 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000923 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000924 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000925 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000926 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000927 &content.entry()->fContent);
928 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000929 }
930 break;
931 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000932 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
933 for (size_t i = 0; i < count; i++) {
934 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000935 &content.entry()->fContent);
936 SkPDFUtils::ClosePath(&content.entry()->fContent);
937 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000938 }
939 break;
940 default:
941 SkASSERT(false);
942 }
943}
944
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000945void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000946 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000947 SkRect r = rect;
948 r.sort();
949
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000950 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000951 if (d.fClip->isEmpty()) {
952 return;
953 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000954 SkPath path;
955 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000956 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000957 return;
958 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000959
epoger@google.comb58772f2013-03-08 09:09:10 +0000960 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000961 return;
962 }
963
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000964 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000965 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000966 return;
967 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000968 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000969 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000970 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000971}
972
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000973void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect,
974 const SkPaint& paint) {
975 SkPath path;
976 path.addRRect(rrect);
977 this->drawPath(draw, path, paint, NULL, true);
978}
979
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000980void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000981 const SkPaint& paint, const SkMatrix* prePathMatrix,
982 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000983 SkPath modifiedPath;
984 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
985
986 SkMatrix matrix = *d.fMatrix;
987 if (prePathMatrix) {
988 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
989 if (!pathIsMutable) {
990 pathPtr = &modifiedPath;
991 pathIsMutable = true;
992 }
993 origPath.transform(*prePathMatrix, pathPtr);
994 } else {
995 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000996 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000997 return;
998 }
999 }
1000 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +00001001
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001002 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001003 if (d.fClip->isEmpty()) {
1004 return;
1005 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001006 if (!pathIsMutable) {
1007 pathPtr = &modifiedPath;
1008 pathIsMutable = true;
1009 }
1010 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001011
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001012 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001013 noEffectPaint.setPathEffect(NULL);
1014 if (fill) {
1015 noEffectPaint.setStyle(SkPaint::kFill_Style);
1016 } else {
1017 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1018 noEffectPaint.setStrokeWidth(0);
1019 }
1020 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001021 return;
1022 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001023
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001024#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001025 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001026 return;
1027 }
1028#endif
1029
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001030 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001031 return;
1032 }
1033
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001034 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001035 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001036 return;
1037 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001038 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1039 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001040 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001041 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001042}
1043
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001044void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1045 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001046 const SkPaint& paint,
1047 SkCanvas::DrawBitmapRectFlags flags) {
1048 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001049 SkMatrix matrix;
1050 SkRect bitmapBounds, tmpSrc, tmpDst;
1051 SkBitmap tmpBitmap;
1052
1053 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1054
1055 // Compute matrix from the two rectangles
1056 if (src) {
1057 tmpSrc = *src;
1058 } else {
1059 tmpSrc = bitmapBounds;
1060 }
1061 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1062
1063 const SkBitmap* bitmapPtr = &bitmap;
1064
1065 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1066 // needed (if the src was clipped). No check needed if src==null.
1067 if (src) {
1068 if (!bitmapBounds.contains(*src)) {
1069 if (!tmpSrc.intersect(bitmapBounds)) {
1070 return; // nothing to draw
1071 }
1072 // recompute dst, based on the smaller tmpSrc
1073 matrix.mapRect(&tmpDst, tmpSrc);
1074 }
1075
1076 // since we may need to clamp to the borders of the src rect within
1077 // the bitmap, we extract a subset.
1078 // TODO: make sure this is handled in drawBitmap and remove from here.
1079 SkIRect srcIR;
1080 tmpSrc.roundOut(&srcIR);
1081 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1082 return;
1083 }
1084 bitmapPtr = &tmpBitmap;
1085
1086 // Since we did an extract, we need to adjust the matrix accordingly
1087 SkScalar dx = 0, dy = 0;
1088 if (srcIR.fLeft > 0) {
1089 dx = SkIntToScalar(srcIR.fLeft);
1090 }
1091 if (srcIR.fTop > 0) {
1092 dy = SkIntToScalar(srcIR.fTop);
1093 }
1094 if (dx || dy) {
1095 matrix.preTranslate(dx, dy);
1096 }
1097 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001098 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001099}
1100
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001101void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001102 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001103 if (d.fClip->isEmpty()) {
1104 return;
1105 }
1106
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001107 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001108 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001109 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1110 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001111}
1112
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001113void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001114 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001115 if (d.fClip->isEmpty()) {
1116 return;
1117 }
1118
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001119 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001120 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001121 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1122 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001123}
1124
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001125void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001126 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001127 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1128 if (paint.getMaskFilter() != NULL) {
1129 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1130 // making text unreadable (e.g. same text twice when using CSS shadows).
1131 return;
1132 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001133 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001134 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001135 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001136 return;
1137 }
1138
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001139 SkGlyphStorage storage(0);
1140 uint16_t* glyphIDs = NULL;
1141 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1142 &glyphIDs);
1143 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001144
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001145 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001146 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001147 content.entry()->fContent.writeText("BT\n");
1148 set_text_transform(x, y, textPaint.getTextSkewX(),
1149 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001150 size_t consumedGlyphCount = 0;
1151 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001152 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1153 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001154 size_t availableGlyphs =
1155 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1156 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001157 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1158 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001159 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001160 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001161 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001162 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001163 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001164 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001165 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001166 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001167}
1168
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001169void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001170 const SkScalar pos[], SkScalar constY,
1171 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001172 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1173 if (paint.getMaskFilter() != NULL) {
1174 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1175 // making text unreadable (e.g. same text twice when using CSS shadows).
1176 return;
1177 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001178 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001179 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001180 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001181 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001182 return;
1183 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001184
djsollen@google.com5df5e612013-10-03 14:42:24 +00001185#ifdef SK_BUILD_FOR_ANDROID
1186 /*
1187 * In the case that we have enabled fallback fonts on Android we need to
1188 * take the following steps to ensure that the PDF draws all characters,
1189 * regardless of their underlying font file, correctly.
1190 *
1191 * 1. Convert input into GlyphID encoding if it currently is not
1192 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1193 * glyph resolves to
1194 * 3. Iterate over those typefaces and recursively call this function with
1195 * only the glyphs (and their positions) that the typeface is capable of
1196 * resolving.
1197 */
1198 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1199 uint16_t* glyphIDs = NULL;
1200 SkGlyphStorage tmpStorage(0);
1201 size_t numGlyphs = 0;
1202
1203 // convert to glyphIDs
1204 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1205 numGlyphs = len / 2;
1206 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1207 } else {
1208 numGlyphs = paint.textToGlyphs(text, len, NULL);
1209 tmpStorage.reset(numGlyphs);
1210 paint.textToGlyphs(text, len, tmpStorage.get());
1211 glyphIDs = tmpStorage.get();
1212 }
1213
1214 // if no typeface is provided in the paint get the default
1215 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1216 if (NULL == origFace.get()) {
1217 origFace.reset(SkTypeface::RefDefault());
1218 }
1219 const uint16_t origGlyphCount = origFace->countGlyphs();
1220
1221 // keep a list of the already visited typefaces and some data about them
1222 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1223
1224 // find all the typefaces needed to resolve this run of text
1225 bool usesOriginalTypeface = false;
1226 for (uint16_t x = 0; x < numGlyphs; ++x) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001227 // optimization that checks to see if original typeface can resolve
1228 // the glyph
djsollen@google.com5df5e612013-10-03 14:42:24 +00001229 if (glyphIDs[x] < origGlyphCount) {
1230 usesOriginalTypeface = true;
1231 continue;
1232 }
1233
1234 // find the fallback typeface that supports this glyph
1235 TypefaceFallbackData data;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001236 data.typeface =
1237 SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1238 paint.getPaintOptionsAndroid(),
1239 &data.lowerBounds,
1240 &data.upperBounds);
djsollen@google.com5df5e612013-10-03 14:42:24 +00001241 // add the typeface and its data if we don't have it
1242 if (data.typeface && !visitedTypefaces.contains(data)) {
1243 visitedTypefaces.push(data);
1244 }
1245 }
1246
1247 // if the original font was used then add it to the list as well
1248 if (usesOriginalTypeface) {
1249 TypefaceFallbackData* data = visitedTypefaces.push();
1250 data->typeface = origFace.get();
1251 data->lowerBounds = 0;
1252 data->upperBounds = origGlyphCount;
1253 }
1254
1255 // keep a scratch glyph and pos storage
1256 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1257 SkScalar* tmpPos = posStorage.get();
1258 SkGlyphStorage glyphStorage(numGlyphs);
1259 uint16_t* tmpGlyphIDs = glyphStorage.get();
1260
1261 // loop through all the valid typefaces, trim the glyphs to only those
1262 // resolved by the typeface, and then draw that run of glyphs
1263 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1264 const TypefaceFallbackData& data = visitedTypefaces[x];
1265
1266 int tmpGlyphCount = 0;
1267 for (uint16_t y = 0; y < numGlyphs; ++y) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001268 if (glyphIDs[y] >= data.lowerBounds &&
1269 glyphIDs[y] < data.upperBounds) {
djsollen@google.com5df5e612013-10-03 14:42:24 +00001270 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1271 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1272 &(pos[y * scalarsPerPos]),
1273 scalarsPerPos * sizeof(SkScalar));
1274 tmpGlyphCount++;
1275 }
1276 }
1277
1278 // recursively call this function with the right typeface
1279 SkPaint tmpPaint = paint;
1280 tmpPaint.setTypeface(data.typeface);
1281 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1282
1283 // turn off fallback chaining
1284 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1285 paintOpts.setUseFontFallbacks(false);
1286 tmpPaint.setPaintOptionsAndroid(paintOpts);
1287
1288 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1289 scalarsPerPos, tmpPaint);
1290 }
1291 return;
1292 }
1293#endif
1294
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001295 SkGlyphStorage storage(0);
1296 uint16_t* glyphIDs = NULL;
1297 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1298 &glyphIDs);
1299 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001300
1301 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001302 content.entry()->fContent.writeText("BT\n");
1303 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001304 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001305 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001306 uint16_t encodedValue = glyphIDs[i];
1307 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001308 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001309 i--;
1310 continue;
1311 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001312 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001313 SkScalar x = pos[i * scalarsPerPos];
1314 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001315 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001316 set_text_transform(x, y, textPaint.getTextSkewX(),
1317 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001318 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001319 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001320 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001321 content.entry()->fContent.writeText(encodedString.c_str());
1322 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001323 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001324 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001325}
1326
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001327void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001328 const SkPath& path, const SkMatrix* matrix,
1329 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001330 if (d.fClip->isEmpty()) {
1331 return;
1332 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001333 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001334}
1335
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001336void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001337 int vertexCount, const SkPoint verts[],
1338 const SkPoint texs[], const SkColor colors[],
1339 SkXfermode* xmode, const uint16_t indices[],
1340 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001341 if (d.fClip->isEmpty()) {
1342 return;
1343 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001344 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001345}
1346
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001347void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1348 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001349 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1350 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001351 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001352 return;
1353 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001354
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001355 // Assume that a vector capable device means that it's a PDF Device.
1356 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001357 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001358 return;
1359 }
1360
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001361 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001362 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001363 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001364 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001365 return;
1366 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001367 if (content.needShape()) {
1368 SkPath shape;
1369 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001370 SkIntToScalar(device->width()),
1371 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001372 content.setShape(shape);
1373 }
1374 if (!content.needSource()) {
1375 return;
1376 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001377
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001378 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1379 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001380 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001381
1382 // Merge glyph sets from the drawn device.
1383 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001384}
1385
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001386void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1387 INHERITED::onAttachToCanvas(canvas);
1388
1389 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1390 fClipStack = canvas->getClipStack();
1391}
1392
1393void SkPDFDevice::onDetachFromCanvas() {
1394 INHERITED::onDetachFromCanvas();
1395
1396 fClipStack = NULL;
1397}
1398
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001399ContentEntry* SkPDFDevice::getLastContentEntry() {
1400 if (fDrawingArea == kContent_DrawingArea) {
1401 return fLastContentEntry;
1402 } else {
1403 return fLastMarginContentEntry;
1404 }
1405}
1406
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001407SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001408 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001409 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001410 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001411 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001412 }
1413}
1414
1415void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1416 if (fDrawingArea == kContent_DrawingArea) {
1417 fLastContentEntry = contentEntry;
1418 } else {
1419 fLastMarginContentEntry = contentEntry;
1420 }
1421}
1422
1423void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001424 // A ScopedContentEntry only exists during the course of a draw call, so
1425 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001426 fDrawingArea = drawingArea;
1427}
1428
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001429SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001430 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001431 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001432
1433 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001434 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001435 fResourceDict->insertResourceAsReference(
1436 SkPDFResourceDict::kExtGState_ResourceType,
1437 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001438 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001439 }
1440
1441 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001442 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001443 fResourceDict->insertResourceAsReference(
1444 SkPDFResourceDict::kXObject_ResourceType,
1445 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001446 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001447 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001448
1449 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001450 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001451 fResourceDict->insertResourceAsReference(
1452 SkPDFResourceDict::kFont_ResourceType,
1453 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001454 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001455 }
1456
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001457 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001458 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001459 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001460 fResourceDict->insertResourceAsReference(
1461 SkPDFResourceDict::kPattern_ResourceType,
1462 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001463 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001464 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001465 }
1466 return fResourceDict;
1467}
1468
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001469const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1470 return fFontResources;
1471}
1472
reed@google.com2a006c12012-09-19 17:05:55 +00001473SkPDFArray* SkPDFDevice::copyMediaBox() const {
1474 // should this be a singleton?
1475 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001476
reed@google.com2a006c12012-09-19 17:05:55 +00001477 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001478 mediaBox->reserve(4);
1479 mediaBox->append(zero.get());
1480 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001481 mediaBox->appendInt(fPageSize.fWidth);
1482 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001483 return mediaBox;
1484}
1485
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001486SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001487 SkMemoryStream* result = new SkMemoryStream;
1488 result->setData(this->copyContentToData())->unref();
1489 return result;
1490}
1491
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001492void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1493 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001494 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1495 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001496 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001497 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001498 SkPoint translation;
1499 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001500 translation.negate();
1501 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1502 translation);
1503 gsState.updateMatrix(entry->fState.fMatrix);
1504 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001505
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001506 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001507 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001508 entry = entry->fNext.get();
1509 }
1510 gsState.drainStack();
1511}
1512
reed@google.com5667afc2011-06-27 14:42:15 +00001513SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001514 SkDynamicMemoryWStream data;
1515 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1516 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001517 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001518
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001519 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1520 // colors the contentArea white before it starts drawing into it and
1521 // that currently acts as our clip.
1522 // Also, think about adding a transform here (or assume that the values
1523 // sent across account for that)
1524 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001525
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001526 // If the content area is the entire page, then we don't need to clip
1527 // the content area (PDF area clips to the page size). Otherwise,
1528 // we have to clip to the content area; we've already applied the
1529 // initial transform, so just clip to the device size.
1530 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001531 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1532 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001533 emit_clip(NULL, &r, &data);
1534 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001535
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001536 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001537
reed@google.com5667afc2011-06-27 14:42:15 +00001538 // potentially we could cache this SkData, and only rebuild it if we
1539 // see that our state has changed.
1540 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001541}
1542
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001543#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001544/* Draws an inverse filled path by using Path Ops to compute the positive
1545 * inverse using the current clip as the inverse bounds.
1546 * Return true if this was an inverse path and was properly handled,
1547 * otherwise returns false and the normal drawing routine should continue,
1548 * either as a (incorrect) fallback or because the path was not inverse
1549 * in the first place.
1550 */
1551bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001552 const SkPaint& paint, bool pathIsMutable,
1553 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001554 if (!origPath.isInverseFillType()) {
1555 return false;
1556 }
1557
1558 if (d.fClip->isEmpty()) {
1559 return false;
1560 }
1561
1562 SkPath modifiedPath;
1563 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1564 SkPaint noInversePaint(paint);
1565
1566 // Merge stroking operations into final path.
1567 if (SkPaint::kStroke_Style == paint.getStyle() ||
1568 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1569 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1570 if (doFillPath) {
1571 noInversePaint.setStyle(SkPaint::kFill_Style);
1572 noInversePaint.setStrokeWidth(0);
1573 pathPtr = &modifiedPath;
1574 } else {
1575 // To be consistent with the raster output, hairline strokes
1576 // are rendered as non-inverted.
1577 modifiedPath.toggleInverseFillType();
1578 drawPath(d, modifiedPath, paint, NULL, true);
1579 return true;
1580 }
1581 }
1582
1583 // Get bounds of clip in current transform space
1584 // (clip bounds are given in device space).
1585 SkRect bounds;
1586 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001587 SkMatrix totalMatrix = *d.fMatrix;
1588 if (prePathMatrix) {
1589 totalMatrix.preConcat(*prePathMatrix);
1590 }
1591 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001592 return false;
1593 }
1594 bounds.set(d.fClip->getBounds());
1595 transformInverse.mapRect(&bounds);
1596
1597 // Extend the bounds by the line width (plus some padding)
1598 // so the edge doesn't cause a visible stroke.
1599 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1600 paint.getStrokeWidth() + SK_Scalar1);
1601
1602 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1603 return false;
1604 }
1605
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001606 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001607 return true;
1608}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001609#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001610
epoger@google.comb58772f2013-03-08 09:09:10 +00001611bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1612 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001613 SkAnnotation* annotationInfo = p.getAnnotation();
1614 if (!annotationInfo) {
1615 return false;
1616 }
1617 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001618 if (urlData) {
1619 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001620 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001621 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001622 SkData* linkToName = annotationInfo->find(
1623 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001624 if (linkToName) {
1625 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001626 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001627 }
1628 return false;
1629}
1630
1631bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1632 const SkMatrix& matrix,
1633 const SkPaint& paint) {
1634 SkAnnotation* annotationInfo = paint.getAnnotation();
1635 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001636 return false;
1637 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001638 SkData* nameData = annotationInfo->find(
1639 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001640 if (nameData) {
1641 for (size_t i = 0; i < count; i++) {
1642 defineNamedDestination(nameData, points[i], matrix);
1643 }
reed@google.com44699382013-10-31 17:28:30 +00001644 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001645 }
1646 return false;
1647}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001648
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001649SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1650 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001651 SkMatrix transform = matrix;
1652 transform.postConcat(fInitialTransform);
1653 SkRect translatedRect;
1654 transform.mapRect(&translatedRect, r);
1655
reed@google.com2a006c12012-09-19 17:05:55 +00001656 if (NULL == fAnnotations) {
1657 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001658 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001659 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001660 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001661 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001662
epoger@google.comb58772f2013-03-08 09:09:10 +00001663 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001664 border->reserve(3);
1665 border->appendInt(0); // Horizontal corner radius.
1666 border->appendInt(0); // Vertical corner radius.
1667 border->appendInt(0); // Width, 0 = no border.
1668 annotation->insert("Border", border.get());
1669
epoger@google.comb58772f2013-03-08 09:09:10 +00001670 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001671 rect->reserve(4);
1672 rect->appendScalar(translatedRect.fLeft);
1673 rect->appendScalar(translatedRect.fTop);
1674 rect->appendScalar(translatedRect.fRight);
1675 rect->appendScalar(translatedRect.fBottom);
1676 annotation->insert("Rect", rect.get());
1677
epoger@google.comb58772f2013-03-08 09:09:10 +00001678 return annotation;
1679}
epoger@google.com1cad8982013-03-06 00:05:13 +00001680
epoger@google.comb58772f2013-03-08 09:09:10 +00001681void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1682 const SkMatrix& matrix) {
1683 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1684
1685 SkString url(static_cast<const char *>(urlData->data()),
1686 urlData->size() - 1);
1687 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1688 action->insertName("S", "URI");
1689 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1690 annotation->insert("A", action.get());
1691}
1692
1693void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1694 const SkMatrix& matrix) {
1695 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1696 SkString name(static_cast<const char *>(nameData->data()),
1697 nameData->size() - 1);
1698 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1699}
1700
1701struct NamedDestination {
1702 const SkData* nameData;
1703 SkPoint point;
1704
1705 NamedDestination(const SkData* nameData, const SkPoint& point)
1706 : nameData(nameData), point(point) {
1707 nameData->ref();
1708 }
1709
1710 ~NamedDestination() {
1711 nameData->unref();
1712 }
1713};
1714
1715void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1716 const SkMatrix& matrix) {
1717 SkMatrix transform = matrix;
1718 transform.postConcat(fInitialTransform);
1719 SkPoint translatedPoint;
1720 transform.mapXY(point.x(), point.y(), &translatedPoint);
1721 fNamedDestinations.push(
1722 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1723}
1724
1725void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1726 int nDest = fNamedDestinations.count();
1727 for (int i = 0; i < nDest; i++) {
1728 NamedDestination* dest = fNamedDestinations[i];
1729 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1730 pdfDest->reserve(5);
1731 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1732 pdfDest->appendName("XYZ");
1733 pdfDest->appendScalar(dest->point.x());
1734 pdfDest->appendScalar(dest->point.y());
1735 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001736 dict->insert(static_cast<const char *>(dest->nameData->data()),
1737 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001738 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001739}
1740
reed@google.comfc641d02012-09-20 17:52:20 +00001741SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1742 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001743 // We always draw the form xobjects that we create back into the device, so
1744 // we simply preserve the font usage instead of pulling it out and merging
1745 // it back in later.
1746 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001747 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001748 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001749}
1750
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001751void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1752 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001753 const SkClipStack* clipStack,
1754 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001755 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001756 bool invertClip) {
1757 if (clipRegion.isEmpty() && !invertClip) {
1758 return;
1759 }
1760
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001761 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1762 SkPDFGraphicState::GetSMaskGraphicState(
1763 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1764
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001765 SkMatrix identity;
1766 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001767 SkPaint paint;
1768 paint.setXfermodeMode(mode);
1769 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001770 if (!content.entry()) {
1771 return;
1772 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001773 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001774 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001775 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001776
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001777 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001778 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001779 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001780}
1781
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001782ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1783 const SkRegion& clipRegion,
1784 const SkMatrix& matrix,
1785 const SkPaint& paint,
1786 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001787 SkPDFFormXObject** dst) {
1788 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001789 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001790 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001791 }
1792
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001793 // The clip stack can come from an SkDraw where it is technically optional.
1794 SkClipStack synthesizedClipStack;
1795 if (clipStack == NULL) {
1796 if (clipRegion == fExistingClipRegion) {
1797 clipStack = &fExistingClipStack;
1798 } else {
1799 // GraphicStackState::updateClip expects the clip stack to have
1800 // fExistingClip as a prefix, so start there, then set the clip
1801 // to the passed region.
1802 synthesizedClipStack = fExistingClipStack;
1803 SkPath clipPath;
1804 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001805 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1806 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001807 clipStack = &synthesizedClipStack;
1808 }
1809 }
1810
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001811 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1812 if (paint.getXfermode()) {
1813 paint.getXfermode()->asMode(&xfermode);
1814 }
1815
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001816 // For the following modes, we want to handle source and destination
1817 // separately, so make an object of what's already there.
1818 if (xfermode == SkXfermode::kClear_Mode ||
1819 xfermode == SkXfermode::kSrc_Mode ||
1820 xfermode == SkXfermode::kSrcIn_Mode ||
1821 xfermode == SkXfermode::kDstIn_Mode ||
1822 xfermode == SkXfermode::kSrcOut_Mode ||
1823 xfermode == SkXfermode::kDstOut_Mode ||
1824 xfermode == SkXfermode::kSrcATop_Mode ||
1825 xfermode == SkXfermode::kDstATop_Mode ||
1826 xfermode == SkXfermode::kModulate_Mode) {
1827 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001828 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001829 SkASSERT(isContentEmpty());
1830 } else if (xfermode != SkXfermode::kSrc_Mode &&
1831 xfermode != SkXfermode::kSrcOut_Mode) {
1832 // Except for Src and SrcOut, if there isn't anything already there,
1833 // then we're done.
1834 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001835 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001836 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001837 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001839
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001840 // Dst xfer mode doesn't draw source at all.
1841 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001842 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001843 }
1844
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001845 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001846 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001847
1848 ContentEntry* lastContentEntry = getLastContentEntry();
1849 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1850 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001851 } else {
1852 newEntry.reset(new ContentEntry);
1853 entry = newEntry.get();
1854 }
1855
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001856 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001857 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001858 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1859 entry->fState.compareInitialState(lastContentEntry->fState)) {
1860 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001861 }
1862
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001863 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001864 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001865 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001866 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001867 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001868 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001869 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001870 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001871 lastContentEntry->fNext.reset(entry);
1872 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001873 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001874 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001875 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001876}
1877
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001878void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001879 SkPDFFormXObject* dst,
1880 SkPath* shape) {
1881 if (xfermode != SkXfermode::kClear_Mode &&
1882 xfermode != SkXfermode::kSrc_Mode &&
1883 xfermode != SkXfermode::kSrcIn_Mode &&
1884 xfermode != SkXfermode::kDstIn_Mode &&
1885 xfermode != SkXfermode::kSrcOut_Mode &&
1886 xfermode != SkXfermode::kDstOut_Mode &&
1887 xfermode != SkXfermode::kSrcATop_Mode &&
1888 xfermode != SkXfermode::kDstATop_Mode &&
1889 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001890 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001891 return;
1892 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001893 if (!dst) {
1894 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1895 xfermode == SkXfermode::kSrcOut_Mode);
1896 return;
1897 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001898
1899 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001900 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001901 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001902 // We have to make a copy of these here because changing the current
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001903 // content into a form-xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001904 SkClipStack clipStack = contentEntries->fState.fClipStack;
1905 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001906
reed@google.comfc641d02012-09-20 17:52:20 +00001907 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001908 if (isContentEmpty()) {
1909 SkASSERT(xfermode == SkXfermode::kClear_Mode);
1910 } else {
1911 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001912 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001913 }
1914
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001915 SkMatrix identity;
1916 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001917
1918 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1919 // without alpha.
1920 if (xfermode == SkXfermode::kSrcATop_Mode) {
1921 // TODO(vandebo): In order to properly support SrcATop we have to track
1922 // the shape of what's been drawn at all times. It's the intersection of
1923 // the non-transparent parts of the device and the outlines (shape) of
1924 // all images and devices drawn.
1925 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1926 &clipStack, clipRegion,
1927 SkXfermode::kSrcOver_Mode, true);
1928 } else {
1929 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1930 SkPDFFormXObject* dstMask = srcFormXObject.get();
1931 if (shape != NULL) {
1932 // Draw shape into a form-xobject.
1933 SkDraw d;
1934 d.fMatrix = &identity;
1935 d.fClip = &clipRegion;
1936 d.fClipStack = &clipStack;
1937 SkPaint filledPaint;
1938 filledPaint.setColor(SK_ColorBLACK);
1939 filledPaint.setStyle(SkPaint::kFill_Style);
1940 this->drawPath(d, *shape, filledPaint, NULL, true);
1941
1942 dstMaskStorage.reset(createFormXObjectFromDevice());
1943 dstMask = dstMaskStorage.get();
1944 }
1945 drawFormXObjectWithMask(addXObjectResource(dst), dstMask, &clipStack,
1946 clipRegion, SkXfermode::kSrcOver_Mode, true);
1947 }
1948
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001949 SkPaint stockPaint;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001950
1951 if (xfermode == SkXfermode::kClear_Mode) {
1952 return;
1953 } else if (xfermode == SkXfermode::kSrc_Mode ||
1954 xfermode == SkXfermode::kDstATop_Mode) {
1955 ScopedContentEntry content(this, &clipStack, clipRegion, identity,
1956 stockPaint);
1957 if (content.entry()) {
1958 SkPDFUtils::DrawFormXObject(
1959 this->addXObjectResource(srcFormXObject.get()),
1960 &content.entry()->fContent);
1961 }
1962 if (xfermode == SkXfermode::kSrc_Mode) {
1963 return;
1964 }
1965 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
1966 ScopedContentEntry content(this, &clipStack, clipRegion, identity,
1967 stockPaint);
1968 if (content.entry()) {
1969 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1970 &content.entry()->fContent);
1971 }
1972 }
1973
1974 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1975 xfermode == SkXfermode::kDstIn_Mode ||
1976 xfermode == SkXfermode::kSrcOut_Mode ||
1977 xfermode == SkXfermode::kDstOut_Mode ||
1978 xfermode == SkXfermode::kSrcATop_Mode ||
1979 xfermode == SkXfermode::kDstATop_Mode ||
1980 xfermode == SkXfermode::kModulate_Mode);
1981
1982 ScopedContentEntry inShapeContentEntry(this, &fExistingClipStack,
1983 fExistingClipRegion, identity,
1984 stockPaint);
1985 if (!inShapeContentEntry.entry()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001986 return;
1987 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001988
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001989 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001990 xfermode == SkXfermode::kSrcOut_Mode ||
1991 xfermode == SkXfermode::kSrcATop_Mode) {
1992 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1993 &clipStack, clipRegion,
1994 SkXfermode::kSrcOver_Mode,
1995 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001996 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001997 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1998 if (xfermode == SkXfermode::kModulate_Mode) {
1999 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
2000 dst, &clipStack, clipRegion,
2001 SkXfermode::kSrcOver_Mode, false);
2002 mode = SkXfermode::kMultiply_Mode;
2003 }
2004 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
2005 &clipStack, clipRegion, mode,
2006 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002007 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002008}
2009
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002010bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002011 ContentEntry* contentEntries = getContentEntries()->get();
2012 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
2013 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002014 return true;
2015 }
2016 return false;
2017}
2018
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002019void SkPDFDevice::populateGraphicStateEntryFromPaint(
2020 const SkMatrix& matrix,
2021 const SkClipStack& clipStack,
2022 const SkRegion& clipRegion,
2023 const SkPaint& paint,
2024 bool hasText,
2025 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002026 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002027
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002028 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
2029 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002030
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002031 entry->fMatrix = matrix;
2032 entry->fClipStack = clipStack;
2033 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002034 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2035 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002036
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002037 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002038 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002039 const SkShader* shader = paint.getShader();
2040 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002041 if (shader) {
2042 // PDF positions patterns relative to the initial transform, so
2043 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002044 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00002045 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002046
2047 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002048 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002049 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00002050
2051 // We need to apply the initial transform to bounds in order to get
2052 // bounds in a consistent coordinate system.
2053 SkRect boundsTemp;
2054 boundsTemp.set(bounds);
2055 fInitialTransform.mapRect(&boundsTemp);
2056 boundsTemp.roundOut(&bounds);
2057
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002058 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002059
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002060 if (pdfShader.get()) {
2061 // pdfShader has been canonicalized so we can directly compare
2062 // pointers.
2063 int resourceIndex = fShaderResources.find(pdfShader.get());
2064 if (resourceIndex < 0) {
2065 resourceIndex = fShaderResources.count();
2066 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002067 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002068 }
2069 entry->fShaderIndex = resourceIndex;
2070 } else {
2071 // A color shader is treated as an invalid shader so we don't have
2072 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002073 SkShader::GradientInfo gradientInfo;
2074 SkColor gradientColor;
2075 gradientInfo.fColors = &gradientColor;
2076 gradientInfo.fColorOffsets = NULL;
2077 gradientInfo.fColorCount = 1;
2078 if (shader->asAGradient(&gradientInfo) ==
2079 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002080 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2081 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002082 }
2083 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002084 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002085
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002086 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002087 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002088 newGraphicState.reset(
2089 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002090 } else {
2091 SkPaint newPaint = paint;
2092 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002093 newGraphicState.reset(
2094 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002095 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002096 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002097 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002098
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002099 if (hasText) {
2100 entry->fTextScaleX = paint.getTextScaleX();
2101 entry->fTextFill = paint.getStyle();
2102 } else {
2103 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002104 }
2105}
2106
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002107int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2108 // Assumes that gs has been canonicalized (so we can directly compare
2109 // pointers).
2110 int result = fGraphicStateResources.find(gs);
2111 if (result < 0) {
2112 result = fGraphicStateResources.count();
2113 fGraphicStateResources.push(gs);
2114 gs->ref();
2115 }
2116 return result;
2117}
2118
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002119int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2120 // Assumes that xobject has been canonicalized (so we can directly compare
2121 // pointers).
2122 int result = fXObjectResources.find(xObject);
2123 if (result < 0) {
2124 result = fXObjectResources.count();
2125 fXObjectResources.push(xObject);
2126 xObject->ref();
2127 }
2128 return result;
2129}
2130
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002131void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2132 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002133 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002134 if (contentEntry->fState.fFont == NULL ||
2135 contentEntry->fState.fTextSize != paint.getTextSize() ||
2136 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002137 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002138 contentEntry->fContent.writeText("/");
2139 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2140 SkPDFResourceDict::kFont_ResourceType,
2141 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002142 contentEntry->fContent.writeText(" ");
2143 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2144 contentEntry->fContent.writeText(" Tf\n");
2145 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002146 }
2147}
2148
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002149int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002150 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2151 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002152 int resourceIndex = fFontResources.find(newFont.get());
2153 if (resourceIndex < 0) {
2154 resourceIndex = fFontResources.count();
2155 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002156 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002157 }
2158 return resourceIndex;
2159}
2160
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002161void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002162 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002163 const SkRegion& origClipRegion,
2164 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002165 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002166 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002167 SkMatrix matrix = origMatrix;
2168 SkRegion perspectiveBounds;
2169 const SkRegion* clipRegion = &origClipRegion;
2170 SkBitmap perspectiveBitmap;
2171 const SkBitmap* bitmap = &origBitmap;
2172 SkBitmap tmpSubsetBitmap;
2173
2174 // Rasterize the bitmap using perspective in a new bitmap.
2175 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002176 if (fRasterDpi == 0) {
2177 return;
2178 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002179 SkBitmap* subsetBitmap;
2180 if (srcRect) {
2181 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2182 return;
2183 }
2184 subsetBitmap = &tmpSubsetBitmap;
2185 } else {
2186 subsetBitmap = &tmpSubsetBitmap;
2187 *subsetBitmap = origBitmap;
2188 }
2189 srcRect = NULL;
2190
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002191 // Transform the bitmap in the new space, without taking into
2192 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002193 SkPath perspectiveOutline;
2194 perspectiveOutline.addRect(
2195 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2196 SkIntToScalar(subsetBitmap->height())));
2197 perspectiveOutline.transform(origMatrix);
2198
2199 // TODO(edisonn): perf - use current clip too.
2200 // Retrieve the bounds of the new shape.
2201 SkRect bounds = perspectiveOutline.getBounds();
2202
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002203 // Transform the bitmap in the new space, taking into
2204 // account the initial transform.
2205 SkMatrix total = origMatrix;
2206 total.postConcat(fInitialTransform);
2207 total.postScale(SkIntToScalar(fRasterDpi) /
2208 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2209 SkIntToScalar(fRasterDpi) /
2210 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2211 SkPath physicalPerspectiveOutline;
2212 physicalPerspectiveOutline.addRect(
2213 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2214 SkIntToScalar(subsetBitmap->height())));
2215 physicalPerspectiveOutline.transform(total);
2216
2217 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2218 bounds.width();
2219 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2220 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002221
2222 // TODO(edisonn): A better approach would be to use a bitmap shader
2223 // (in clamp mode) and draw a rect over the entire bounding box. Then
2224 // intersect perspectiveOutline to the clip. That will avoid introducing
2225 // alpha to the image while still giving good behavior at the edge of
2226 // the image. Avoiding alpha will reduce the pdf size and generation
2227 // CPU time some.
2228
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002229 perspectiveBitmap.setConfig(
2230 SkBitmap::kARGB_8888_Config,
2231 SkScalarCeilToInt(
2232 physicalPerspectiveOutline.getBounds().width()),
2233 SkScalarCeilToInt(
2234 physicalPerspectiveOutline.getBounds().height()));
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002235 perspectiveBitmap.allocPixels();
2236 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2237
2238 SkBitmapDevice device(perspectiveBitmap);
2239 SkCanvas canvas(&device);
2240
2241 SkScalar deltaX = bounds.left();
2242 SkScalar deltaY = bounds.top();
2243
2244 SkMatrix offsetMatrix = origMatrix;
2245 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002246 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002247
2248 // Translate the draw in the new canvas, so we perfectly fit the
2249 // shape in the bitmap.
2250 canvas.setMatrix(offsetMatrix);
2251
2252 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2253
2254 // Make sure the final bits are in the bitmap.
2255 canvas.flush();
2256
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002257 // In the new space, we use the identity matrix translated
2258 // and scaled to reflect DPI.
2259 matrix.setScale(1 / scaleX, 1 / scaleY);
2260 matrix.postTranslate(deltaX, deltaY);
2261
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002262 perspectiveBounds.setRect(
2263 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2264 SkScalarFloorToInt(bounds.y()),
2265 SkScalarCeilToInt(bounds.width()),
2266 SkScalarCeilToInt(bounds.height())));
2267 clipRegion = &perspectiveBounds;
2268 srcRect = NULL;
2269 bitmap = &perspectiveBitmap;
2270 }
2271
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002272 SkMatrix scaled;
2273 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002274 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2275 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002276 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002277 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002278 scaled.postScale(SkIntToScalar(subset.width()),
2279 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002280 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002281 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002282 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2283 return;
2284 }
2285 if (content.needShape()) {
2286 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002287 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2288 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002289 shape.transform(matrix);
2290 content.setShape(shape);
2291 }
2292 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002293 return;
2294 }
2295
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002296 SkAutoTUnref<SkPDFImage> image(
2297 SkPDFImage::CreateImage(*bitmap, subset, fEncoder));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002298 if (!image) {
2299 return;
2300 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002301
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002302 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002303 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002304}
reed@google.com982cb872011-12-07 18:34:08 +00002305
2306bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2307 SkCanvas::Config8888) {
2308 return false;
2309}
reed@google.comb55deeb2012-01-06 14:43:09 +00002310
2311bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2312 return false;
2313}