blob: a7d2bd459accb39c70518ef21afc1289b30d3723 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000015#include "SkFontHost.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000016#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000018#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
23#include "SkPDFImage.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000024#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000026#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000029#include "SkRect.h"
30#include "SkString.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000031#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000032#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000033#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000034#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000035
djsollen@google.com5df5e612013-10-03 14:42:24 +000036#ifdef SK_BUILD_FOR_ANDROID
37#include "SkTypeface_android.h"
38
39struct TypefaceFallbackData {
40 SkTypeface* typeface;
41 int lowerBounds;
42 int upperBounds;
43
44 bool operator==(const TypefaceFallbackData& b) const {
45 return typeface == b.typeface &&
46 lowerBounds == b.lowerBounds &&
47 upperBounds == b.upperBounds;
48 }
49};
50#endif
51
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000052// Utility functions
53
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000054static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000055 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
56 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000057 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000058 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
59 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000060 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000061 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
62 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000063 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000064 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
65 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000066}
67
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000068static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000069 SkPaint result = paint;
70 if (result.isFakeBoldText()) {
71 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
72 kStdFakeBoldInterpKeys,
73 kStdFakeBoldInterpValues,
74 kStdFakeBoldInterpLength);
75 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000076 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000077 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000078 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000079 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000080 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000081 result.setStrokeWidth(width);
82 }
83 return result;
84}
85
86// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000087static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000088 const uint16_t* glyphs, size_t len,
89 SkScalar* x, SkScalar* y) {
90 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000091 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000092 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000093
94 SkMatrix ident;
95 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000096 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000097 SkGlyphCache* cache = autoCache.getCache();
98
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000099 const char* start = reinterpret_cast<const char*>(glyphs);
100 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000101 SkFixed xAdv = 0, yAdv = 0;
102
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000103 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000104 while (start < stop) {
105 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
106 xAdv += glyph.fAdvanceX;
107 yAdv += glyph.fAdvanceY;
108 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000109 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000110 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000111 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000112
113 SkScalar xAdj = SkFixedToScalar(xAdv);
114 SkScalar yAdj = SkFixedToScalar(yAdv);
115 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
116 xAdj = SkScalarHalf(xAdj);
117 yAdj = SkScalarHalf(yAdj);
118 }
119 *x = *x - xAdj;
120 *y = *y - yAdj;
121}
122
reed@google.comfed86bd2013-03-14 15:04:57 +0000123static size_t max_glyphid_for_typeface(SkTypeface* typeface) {
124 SkAutoResolveDefaultTypeface autoResolve(typeface);
125 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000126 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000127}
128
129typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
130
131static size_t force_glyph_encoding(const SkPaint& paint, const void* text,
132 size_t len, SkGlyphStorage* storage,
133 uint16_t** glyphIDs) {
134 // Make sure we have a glyph id encoding.
135 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
136 size_t numGlyphs = paint.textToGlyphs(text, len, NULL);
137 storage->reset(numGlyphs);
138 paint.textToGlyphs(text, len, storage->get());
139 *glyphIDs = storage->get();
140 return numGlyphs;
141 }
142
143 // For user supplied glyph ids we need to validate them.
144 SkASSERT((len & 1) == 0);
145 size_t numGlyphs = len / 2;
146 const uint16_t* input =
147 reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
148
149 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
150 size_t validated;
151 for (validated = 0; validated < numGlyphs; ++validated) {
152 if (input[validated] > maxGlyphID) {
153 break;
154 }
155 }
156 if (validated >= numGlyphs) {
157 *glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
158 return numGlyphs;
159 }
160
161 // Silently drop anything out of range.
162 storage->reset(numGlyphs);
163 if (validated > 0) {
164 memcpy(storage->get(), input, validated * sizeof(uint16_t));
165 }
166
167 for (size_t i = validated; i < numGlyphs; ++i) {
168 storage->get()[i] = input[i];
169 if (input[i] > maxGlyphID) {
170 storage->get()[i] = 0;
171 }
172 }
173 *glyphIDs = storage->get();
174 return numGlyphs;
175}
176
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000177static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
178 SkWStream* content) {
179 // Flip the text about the x-axis to account for origin swap and include
180 // the passed parameters.
181 content->writeText("1 0 ");
182 SkPDFScalar::Append(0 - textSkewX, content);
183 content->writeText(" -1 ");
184 SkPDFScalar::Append(x, content);
185 content->writeText(" ");
186 SkPDFScalar::Append(y, content);
187 content->writeText(" Tm\n");
188}
189
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000190// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
191// later being our representation of an object in the PDF file.
192struct GraphicStateEntry {
193 GraphicStateEntry();
194
195 // Compare the fields we care about when setting up a new content entry.
196 bool compareInitialState(const GraphicStateEntry& b);
197
198 SkMatrix fMatrix;
199 // We can't do set operations on Paths, though PDF natively supports
200 // intersect. If the clip stack does anything other than intersect,
201 // we have to fall back to the region. Treat fClipStack as authoritative.
202 // See http://code.google.com/p/skia/issues/detail?id=221
203 SkClipStack fClipStack;
204 SkRegion fClipRegion;
205
206 // When emitting the content entry, we will ensure the graphic state
207 // is set to these values first.
208 SkColor fColor;
209 SkScalar fTextScaleX; // Zero means we don't care what the value is.
210 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
211 int fShaderIndex;
212 int fGraphicStateIndex;
213
214 // We may change the font (i.e. for Type1 support) within a
215 // ContentEntry. This is the one currently in effect, or NULL if none.
216 SkPDFFont* fFont;
217 // In PDF, text size has no default value. It is only valid if fFont is
218 // not NULL.
219 SkScalar fTextSize;
220};
221
222GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
223 fTextScaleX(SK_Scalar1),
224 fTextFill(SkPaint::kFill_Style),
225 fShaderIndex(-1),
226 fGraphicStateIndex(-1),
227 fFont(NULL),
228 fTextSize(SK_ScalarNaN) {
229 fMatrix.reset();
230}
231
232bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& b) {
233 return fColor == b.fColor &&
234 fShaderIndex == b.fShaderIndex &&
235 fGraphicStateIndex == b.fGraphicStateIndex &&
236 fMatrix == b.fMatrix &&
237 fClipStack == b.fClipStack &&
238 (fTextScaleX == 0 ||
239 b.fTextScaleX == 0 ||
240 (fTextScaleX == b.fTextScaleX && fTextFill == b.fTextFill));
241}
242
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000243class GraphicStackState {
244public:
245 GraphicStackState(const SkClipStack& existingClipStack,
246 const SkRegion& existingClipRegion,
247 SkWStream* contentStream)
248 : fStackDepth(0),
249 fContentStream(contentStream) {
250 fEntries[0].fClipStack = existingClipStack;
251 fEntries[0].fClipRegion = existingClipRegion;
252 }
253
254 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000255 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000256 void updateMatrix(const SkMatrix& matrix);
257 void updateDrawingState(const GraphicStateEntry& state);
258
259 void drainStack();
260
261private:
262 void push();
263 void pop();
264 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
265
266 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
267 static const int kMaxStackDepth = 12;
268 GraphicStateEntry fEntries[kMaxStackDepth + 1];
269 int fStackDepth;
270 SkWStream* fContentStream;
271};
272
273void GraphicStackState::drainStack() {
274 while (fStackDepth) {
275 pop();
276 }
277}
278
279void GraphicStackState::push() {
280 SkASSERT(fStackDepth < kMaxStackDepth);
281 fContentStream->writeText("q\n");
282 fStackDepth++;
283 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
284}
285
286void GraphicStackState::pop() {
287 SkASSERT(fStackDepth > 0);
288 fContentStream->writeText("Q\n");
289 fStackDepth--;
290}
291
robertphillips@google.com80214e22012-07-20 15:33:18 +0000292// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000293// and then skips over the leading entries as specified in prefix. It requires
294// and asserts that "prefix" will be a prefix to "stack."
295static void skip_clip_stack_prefix(const SkClipStack& prefix,
296 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000297 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000298 SkClipStack::B2TIter prefixIter(prefix);
299 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000300
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000301 const SkClipStack::Element* prefixEntry;
302 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000303
304 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000305 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000306 iterEntry = iter->next();
307 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000308 // Because of SkClipStack does internal intersection, the last clip
309 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000310 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000311 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
312 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
313 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000314 // back up the iterator by one
315 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000316 prefixEntry = prefixIter.next();
317 break;
318 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000319 }
320
321 SkASSERT(prefixEntry == NULL);
322}
323
324static void emit_clip(SkPath* clipPath, SkRect* clipRect,
325 SkWStream* contentStream) {
326 SkASSERT(clipPath || clipRect);
327
328 SkPath::FillType clipFill;
329 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000330 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000331 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000332 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000333 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
334 clipFill = SkPath::kWinding_FillType;
335 }
336
337 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
338 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
339 if (clipFill == SkPath::kEvenOdd_FillType) {
340 contentStream->writeText("W* n\n");
341 } else {
342 contentStream->writeText("W n\n");
343 }
344}
345
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000346#ifdef SK_PDF_USE_PATHOPS
347/* Calculate an inverted path's equivalent non-inverted path, given the
348 * canvas bounds.
349 * outPath may alias with invPath (since this is supported by PathOps).
350 */
351static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
352 SkPath* outPath) {
353 SkASSERT(invPath.isInverseFillType());
354
355 SkPath clipPath;
356 clipPath.addRect(bounds);
357
358 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
359}
360
361// Sanity check the numerical values of the SkRegion ops and PathOps ops
362// enums so region_op_to_pathops_op can do a straight passthrough cast.
363// If these are failing, it may be necessary to make region_op_to_pathops_op
364// do more.
365SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
366 region_pathop_mismatch);
367SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
368 region_pathop_mismatch);
369SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
370 region_pathop_mismatch);
371SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
372 region_pathop_mismatch);
373SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
374 (int)kReverseDifference_PathOp,
375 region_pathop_mismatch);
376
377static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
378 SkASSERT(op >= 0);
379 SkASSERT(op <= SkRegion::kReverseDifference_Op);
380 return (SkPathOp)op;
381}
382
383/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
384 * Returns true if successful, or false if not successful.
385 * If successful, the resulting clip is stored in outClipPath.
386 * If not successful, outClipPath is undefined, and a fallback method
387 * should be used.
388 */
389static bool get_clip_stack_path(const SkMatrix& transform,
390 const SkClipStack& clipStack,
391 const SkRegion& clipRegion,
392 SkPath* outClipPath) {
393 outClipPath->reset();
394 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
395
396 const SkClipStack::Element* clipEntry;
397 SkClipStack::Iter iter;
398 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
399 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
400 SkPath entryPath;
401 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
402 outClipPath->reset();
403 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
404 continue;
405 } else if (SkClipStack::Element::kRect_Type == clipEntry->getType()) {
406 entryPath.addRect(clipEntry->getRect());
407 } else if (SkClipStack::Element::kPath_Type == clipEntry->getType()) {
408 entryPath = clipEntry->getPath();
409 }
410 entryPath.transform(transform);
411
412 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
413 *outClipPath = entryPath;
414 } else {
415 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
416 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
417 return false;
418 }
419 }
420 }
421
422 if (outClipPath->isInverseFillType()) {
423 // The bounds are slightly outset to ensure this is correct in the
424 // face of floating-point accuracy and possible SkRegion bitmap
425 // approximations.
426 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
427 clipBounds.outset(SK_Scalar1, SK_Scalar1);
428 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
429 return false;
430 }
431 }
432 return true;
433}
434#endif
435
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000436// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000437// graphic state stack, and the fact that we can know all the clips used
438// on the page to optimize this.
439void GraphicStackState::updateClip(const SkClipStack& clipStack,
440 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000441 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000442 if (clipStack == currentEntry()->fClipStack) {
443 return;
444 }
445
446 while (fStackDepth > 0) {
447 pop();
448 if (clipStack == currentEntry()->fClipStack) {
449 return;
450 }
451 }
452 push();
453
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000454 currentEntry()->fClipStack = clipStack;
455 currentEntry()->fClipRegion = clipRegion;
456
457 SkMatrix transform;
458 transform.setTranslate(translation.fX, translation.fY);
459
460#ifdef SK_PDF_USE_PATHOPS
461 SkPath clipPath;
462 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
463 emit_clip(&clipPath, NULL, fContentStream);
464 return;
465 }
466#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000467 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
468 // already been applied. (If this is a top level device, then it specifies
469 // a clip to the content area. If this is a layer, then it specifies
470 // the clip in effect when the layer was created.) There's no need to
471 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
472 // initial clip on the parent layer. (This means there's a bug if the user
473 // expands the clip and then uses any xfer mode that uses dst:
474 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000475 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000476 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
477
478 // If the clip stack does anything other than intersect or if it uses
479 // an inverse fill type, we have to fall back to the clip region.
480 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000481 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000482 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000483 if (clipEntry->getOp() != SkRegion::kIntersect_Op || clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000484 needRegion = true;
485 break;
486 }
487 }
488
489 if (needRegion) {
490 SkPath clipPath;
491 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
492 emit_clip(&clipPath, NULL, fContentStream);
493 } else {
494 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000495 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000496 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000497 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
498 switch (clipEntry->getType()) {
499 case SkClipStack::Element::kRect_Type: {
500 SkRect translatedClip;
501 transform.mapRect(&translatedClip, clipEntry->getRect());
502 emit_clip(NULL, &translatedClip, fContentStream);
503 break;
504 }
505 case SkClipStack::Element::kPath_Type: {
506 SkPath translatedPath;
507 clipEntry->getPath().transform(transform, &translatedPath);
508 emit_clip(&translatedPath, NULL, fContentStream);
509 break;
510 }
511 default:
512 SkASSERT(false);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000513 }
514 }
515 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000516}
517
518void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
519 if (matrix == currentEntry()->fMatrix) {
520 return;
521 }
522
523 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
524 SkASSERT(fStackDepth > 0);
525 SkASSERT(fEntries[fStackDepth].fClipStack ==
526 fEntries[fStackDepth -1].fClipStack);
527 pop();
528
529 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
530 }
531 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
532 return;
533 }
534
535 push();
536 SkPDFUtils::AppendTransform(matrix, fContentStream);
537 currentEntry()->fMatrix = matrix;
538}
539
540void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
541 // PDF treats a shader as a color, so we only set one or the other.
542 if (state.fShaderIndex >= 0) {
543 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000544 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000545 currentEntry()->fShaderIndex = state.fShaderIndex;
546 }
547 } else {
548 if (state.fColor != currentEntry()->fColor ||
549 currentEntry()->fShaderIndex >= 0) {
550 emit_pdf_color(state.fColor, fContentStream);
551 fContentStream->writeText("RG ");
552 emit_pdf_color(state.fColor, fContentStream);
553 fContentStream->writeText("rg\n");
554 currentEntry()->fColor = state.fColor;
555 currentEntry()->fShaderIndex = -1;
556 }
557 }
558
559 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000560 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000561 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
562 }
563
564 if (state.fTextScaleX) {
565 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
566 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
567 SkIntToScalar(100));
568 SkPDFScalar::Append(pdfScale, fContentStream);
569 fContentStream->writeText(" Tz\n");
570 currentEntry()->fTextScaleX = state.fTextScaleX;
571 }
572 if (state.fTextFill != currentEntry()->fTextFill) {
573 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
574 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
575 enum_must_match_value);
576 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
577 enum_must_match_value);
578 fContentStream->writeDecAsText(state.fTextFill);
579 fContentStream->writeText(" Tr\n");
580 currentEntry()->fTextFill = state.fTextFill;
581 }
582 }
583}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000584
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000585SkBaseDevice* SkPDFDevice::onCreateCompatibleDevice(SkBitmap::Config config,
586 int width, int height,
587 bool isOpaque,
588 Usage usage) {
bsalomon@google.come97f0852011-06-17 13:10:25 +0000589 SkMatrix initialTransform;
590 initialTransform.reset();
591 SkISize size = SkISize::Make(width, height);
592 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
593}
594
595
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000596struct ContentEntry {
597 GraphicStateEntry fState;
598 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000599 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000600
601 // If the stack is too deep we could get Stack Overflow.
602 // So we manually destruct the object.
603 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000604 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000605 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000606 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000607 // When the destructor is called, fNext is NULL and exits.
608 delete val;
609 val = valNext;
610 }
611 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000612};
613
614// A helper class to automatically finish a ContentEntry at the end of a
615// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000616class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000617public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000618 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
619 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 : fDevice(device),
621 fContentEntry(NULL),
622 fXfermode(SkXfermode::kSrcOver_Mode) {
623 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
624 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000625 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
626 const SkRegion& clipRegion, const SkMatrix& matrix,
627 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000628 : fDevice(device),
629 fContentEntry(NULL),
630 fXfermode(SkXfermode::kSrcOver_Mode) {
631 init(clipStack, clipRegion, matrix, paint, hasText);
632 }
633
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000634 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000635 if (fContentEntry) {
reed@google.comfc641d02012-09-20 17:52:20 +0000636 fDevice->finishContentEntry(fXfermode, fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000637 }
reed@google.comfc641d02012-09-20 17:52:20 +0000638 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000639 }
640
641 ContentEntry* entry() { return fContentEntry; }
642private:
643 SkPDFDevice* fDevice;
644 ContentEntry* fContentEntry;
645 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000646 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000647
648 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
649 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
reed@google.comfc641d02012-09-20 17:52:20 +0000650 fDstFormXObject = NULL;
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000651 // Shape has to be flatten before we get here.
652 if (matrix.hasPerspective()) {
653 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000654 return;
655 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000656 if (paint.getXfermode()) {
657 paint.getXfermode()->asMode(&fXfermode);
658 }
659 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
660 matrix, paint, hasText,
661 &fDstFormXObject);
662 }
663};
664
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000665////////////////////////////////////////////////////////////////////////////////
666
ctguil@chromium.org15261292011-04-29 17:54:16 +0000667static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000668 const SkMatrix* initialTransform) {
reed@android.comf2b98d62010-12-20 18:26:13 +0000669 SkBitmap bitmap;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000670 if (initialTransform) {
671 // Compute the size of the drawing area.
672 SkVector drawingSize;
673 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000674 drawingSize.set(SkIntToScalar(contentSize.fWidth),
675 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000676 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000677 // This shouldn't happen, initial transform should be invertible.
678 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000679 inverse.reset();
680 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000681 inverse.mapVectors(&drawingSize, 1);
682 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
683 bitmap.setConfig(SkBitmap::kNo_Config, abs(size.fWidth),
684 abs(size.fHeight));
685 } else {
686 bitmap.setConfig(SkBitmap::kNo_Config, abs(contentSize.fWidth),
687 abs(contentSize.fHeight));
688 }
689
reed@android.comf2b98d62010-12-20 18:26:13 +0000690 return bitmap;
691}
692
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000693// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000694SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000695 const SkMatrix& initialTransform)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000696 : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
ctguil@chromium.org15261292011-04-29 17:54:16 +0000697 fPageSize(pageSize),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000698 fContentSize(contentSize),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000699 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000700 fLastMarginContentEntry(NULL),
edisonn@google.comd9dfa182013-04-24 13:01:01 +0000701 fClipStack(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000702 fEncoder(NULL),
703 fRasterDpi(SkFloatToScalar(72.0f)) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000704 // Just report that PDF does not supports perspective in the
705 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000706 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
707
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000708 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000709 // origin at the bottom left. This matrix corrects for that. But that only
710 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000711 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
712 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000713 fInitialTransform.preConcat(initialTransform);
714
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000715 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000716 fExistingClipRegion.setRect(existingClip);
717
718 this->init();
719}
720
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000721// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000722SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
723 const SkClipStack& existingClipStack,
724 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000725 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000726 fPageSize(layerSize),
727 fContentSize(layerSize),
728 fExistingClipStack(existingClipStack),
729 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000730 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000731 fLastMarginContentEntry(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000732 fClipStack(NULL),
733 fEncoder(NULL),
734 fRasterDpi(SkFloatToScalar(72.0f)) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000735 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000736 this->init();
737}
738
739SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000740 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000741}
742
743void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000744 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000745 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000746 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000747 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000748 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000749 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000750 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000751 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000752 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
753 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000754}
755
vandebo@chromium.org98594282011-07-25 22:34:12 +0000756void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000757 fGraphicStateResources.unrefAll();
758 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000759 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000760 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000761 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000762 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000763 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000764
vandebo@chromium.org98594282011-07-25 22:34:12 +0000765 if (clearFontUsage) {
766 fFontGlyphUsage->reset();
767 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000768}
769
reed@google.com982cb872011-12-07 18:34:08 +0000770uint32_t SkPDFDevice::getDeviceCapabilities() {
771 return kVector_Capability;
772}
773
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000774void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000775 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000776 this->init();
777
778 SkPaint paint;
779 paint.setColor(color);
780 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000781 SkMatrix identity;
782 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000783 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
784 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000785 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000786}
787
788void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000789 SkPaint newPaint = paint;
790 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000791 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000792 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000793}
794
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000795void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
796 ContentEntry* contentEntry) {
797 if (!contentEntry) {
798 return;
799 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000800 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
801 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000802 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000803 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000804 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000805 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000806 inverse.mapRect(&bbox);
807
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000808 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000809 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000810 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000811}
812
813void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
814 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000815 const SkPaint& passedPaint) {
816 if (count == 0) {
817 return;
818 }
819
epoger@google.comb58772f2013-03-08 09:09:10 +0000820 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
821 return;
822 }
823
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000824 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
825 // We only use this when there's a path effect because of the overhead
826 // of multiple calls to setUpContentEntry it causes.
827 if (passedPaint.getPathEffect()) {
828 if (d.fClip->isEmpty()) {
829 return;
830 }
831 SkDraw pointDraw(d);
832 pointDraw.fDevice = this;
833 pointDraw.drawPoints(mode, count, points, passedPaint, true);
834 return;
835 }
836
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000837 const SkPaint* paint = &passedPaint;
838 SkPaint modifiedPaint;
839
840 if (mode == SkCanvas::kPoints_PointMode &&
841 paint->getStrokeCap() != SkPaint::kRound_Cap) {
842 modifiedPaint = *paint;
843 paint = &modifiedPaint;
844 if (paint->getStrokeWidth()) {
845 // PDF won't draw a single point with square/butt caps because the
846 // orientation is ambiguous. Draw a rectangle instead.
847 modifiedPaint.setStyle(SkPaint::kFill_Style);
848 SkScalar strokeWidth = paint->getStrokeWidth();
849 SkScalar halfStroke = SkScalarHalf(strokeWidth);
850 for (size_t i = 0; i < count; i++) {
851 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
852 r.inset(-halfStroke, -halfStroke);
853 drawRect(d, r, modifiedPaint);
854 }
855 return;
856 } else {
857 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
858 }
859 }
860
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000861 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000862 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000863 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000864 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000865
866 switch (mode) {
867 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000868 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000869 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000870 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000871 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000872 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000873 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000874 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000875 break;
876 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000877 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000878 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000879 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000880 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000881 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000882 &content.entry()->fContent);
883 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000884 }
885 break;
886 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000887 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
888 for (size_t i = 0; i < count; i++) {
889 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000890 &content.entry()->fContent);
891 SkPDFUtils::ClosePath(&content.entry()->fContent);
892 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000893 }
894 break;
895 default:
896 SkASSERT(false);
897 }
898}
899
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000900void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000901 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000902 SkRect r = rect;
903 r.sort();
904
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000905 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000906 if (d.fClip->isEmpty()) {
907 return;
908 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000909 SkPath path;
910 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000911 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000912 return;
913 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000914
epoger@google.comb58772f2013-03-08 09:09:10 +0000915 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000916 return;
917 }
918
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000919 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000920 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000921 return;
922 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000923 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000924 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000925 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000926}
927
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000928void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000929 const SkPaint& paint, const SkMatrix* prePathMatrix,
930 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000931 SkPath modifiedPath;
932 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
933
934 SkMatrix matrix = *d.fMatrix;
935 if (prePathMatrix) {
936 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
937 if (!pathIsMutable) {
938 pathPtr = &modifiedPath;
939 pathIsMutable = true;
940 }
941 origPath.transform(*prePathMatrix, pathPtr);
942 } else {
943 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000944 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000945 return;
946 }
947 }
948 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000949
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000950 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000951 if (d.fClip->isEmpty()) {
952 return;
953 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000954 if (!pathIsMutable) {
955 pathPtr = &modifiedPath;
956 pathIsMutable = true;
957 }
958 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000959
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000960 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000961 noEffectPaint.setPathEffect(NULL);
962 if (fill) {
963 noEffectPaint.setStyle(SkPaint::kFill_Style);
964 } else {
965 noEffectPaint.setStyle(SkPaint::kStroke_Style);
966 noEffectPaint.setStrokeWidth(0);
967 }
968 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000969 return;
970 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000971
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000972#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000973 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000974 return;
975 }
976#endif
977
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000978 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000979 return;
980 }
981
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000982 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000983 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000984 return;
985 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000986 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
987 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000988 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000989 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000990}
991
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000992void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
993 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000994 const SkPaint& paint,
995 SkCanvas::DrawBitmapRectFlags flags) {
996 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000997 SkMatrix matrix;
998 SkRect bitmapBounds, tmpSrc, tmpDst;
999 SkBitmap tmpBitmap;
1000
1001 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1002
1003 // Compute matrix from the two rectangles
1004 if (src) {
1005 tmpSrc = *src;
1006 } else {
1007 tmpSrc = bitmapBounds;
1008 }
1009 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1010
1011 const SkBitmap* bitmapPtr = &bitmap;
1012
1013 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1014 // needed (if the src was clipped). No check needed if src==null.
1015 if (src) {
1016 if (!bitmapBounds.contains(*src)) {
1017 if (!tmpSrc.intersect(bitmapBounds)) {
1018 return; // nothing to draw
1019 }
1020 // recompute dst, based on the smaller tmpSrc
1021 matrix.mapRect(&tmpDst, tmpSrc);
1022 }
1023
1024 // since we may need to clamp to the borders of the src rect within
1025 // the bitmap, we extract a subset.
1026 // TODO: make sure this is handled in drawBitmap and remove from here.
1027 SkIRect srcIR;
1028 tmpSrc.roundOut(&srcIR);
1029 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1030 return;
1031 }
1032 bitmapPtr = &tmpBitmap;
1033
1034 // Since we did an extract, we need to adjust the matrix accordingly
1035 SkScalar dx = 0, dy = 0;
1036 if (srcIR.fLeft > 0) {
1037 dx = SkIntToScalar(srcIR.fLeft);
1038 }
1039 if (srcIR.fTop > 0) {
1040 dy = SkIntToScalar(srcIR.fTop);
1041 }
1042 if (dx || dy) {
1043 matrix.preTranslate(dx, dy);
1044 }
1045 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001046 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001047}
1048
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001049void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001050 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001051 if (d.fClip->isEmpty()) {
1052 return;
1053 }
1054
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001055 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001056 transform.postConcat(*d.fMatrix);
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001057 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001058}
1059
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001060void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001061 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001062 if (d.fClip->isEmpty()) {
1063 return;
1064 }
1065
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001066 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001067 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001068 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001069}
1070
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001071void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001072 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001073 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1074 if (paint.getMaskFilter() != NULL) {
1075 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1076 // making text unreadable (e.g. same text twice when using CSS shadows).
1077 return;
1078 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001079 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001080 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001081 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001082 return;
1083 }
1084
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001085 SkGlyphStorage storage(0);
1086 uint16_t* glyphIDs = NULL;
1087 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1088 &glyphIDs);
1089 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001090
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001091 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001092 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001093 content.entry()->fContent.writeText("BT\n");
1094 set_text_transform(x, y, textPaint.getTextSkewX(),
1095 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001096 size_t consumedGlyphCount = 0;
1097 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001098 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1099 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001100 size_t availableGlyphs =
1101 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1102 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001103 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1104 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001105 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001106 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001107 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001108 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001109 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001110 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001111 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001112 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001113}
1114
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001115void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001116 const SkScalar pos[], SkScalar constY,
1117 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001118 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1119 if (paint.getMaskFilter() != NULL) {
1120 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1121 // making text unreadable (e.g. same text twice when using CSS shadows).
1122 return;
1123 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001124 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001125 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001126 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001127 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001128 return;
1129 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001130
djsollen@google.com5df5e612013-10-03 14:42:24 +00001131#ifdef SK_BUILD_FOR_ANDROID
1132 /*
1133 * In the case that we have enabled fallback fonts on Android we need to
1134 * take the following steps to ensure that the PDF draws all characters,
1135 * regardless of their underlying font file, correctly.
1136 *
1137 * 1. Convert input into GlyphID encoding if it currently is not
1138 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1139 * glyph resolves to
1140 * 3. Iterate over those typefaces and recursively call this function with
1141 * only the glyphs (and their positions) that the typeface is capable of
1142 * resolving.
1143 */
1144 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1145 uint16_t* glyphIDs = NULL;
1146 SkGlyphStorage tmpStorage(0);
1147 size_t numGlyphs = 0;
1148
1149 // convert to glyphIDs
1150 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1151 numGlyphs = len / 2;
1152 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1153 } else {
1154 numGlyphs = paint.textToGlyphs(text, len, NULL);
1155 tmpStorage.reset(numGlyphs);
1156 paint.textToGlyphs(text, len, tmpStorage.get());
1157 glyphIDs = tmpStorage.get();
1158 }
1159
1160 // if no typeface is provided in the paint get the default
1161 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1162 if (NULL == origFace.get()) {
1163 origFace.reset(SkTypeface::RefDefault());
1164 }
1165 const uint16_t origGlyphCount = origFace->countGlyphs();
1166
1167 // keep a list of the already visited typefaces and some data about them
1168 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1169
1170 // find all the typefaces needed to resolve this run of text
1171 bool usesOriginalTypeface = false;
1172 for (uint16_t x = 0; x < numGlyphs; ++x) {
1173 // optimization that checks to see if original typeface can resolve the glyph
1174 if (glyphIDs[x] < origGlyphCount) {
1175 usesOriginalTypeface = true;
1176 continue;
1177 }
1178
1179 // find the fallback typeface that supports this glyph
1180 TypefaceFallbackData data;
1181 data.typeface = SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1182 paint.getPaintOptionsAndroid(),
1183 &data.lowerBounds, &data.upperBounds);
1184 // add the typeface and its data if we don't have it
1185 if (data.typeface && !visitedTypefaces.contains(data)) {
1186 visitedTypefaces.push(data);
1187 }
1188 }
1189
1190 // if the original font was used then add it to the list as well
1191 if (usesOriginalTypeface) {
1192 TypefaceFallbackData* data = visitedTypefaces.push();
1193 data->typeface = origFace.get();
1194 data->lowerBounds = 0;
1195 data->upperBounds = origGlyphCount;
1196 }
1197
1198 // keep a scratch glyph and pos storage
1199 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1200 SkScalar* tmpPos = posStorage.get();
1201 SkGlyphStorage glyphStorage(numGlyphs);
1202 uint16_t* tmpGlyphIDs = glyphStorage.get();
1203
1204 // loop through all the valid typefaces, trim the glyphs to only those
1205 // resolved by the typeface, and then draw that run of glyphs
1206 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1207 const TypefaceFallbackData& data = visitedTypefaces[x];
1208
1209 int tmpGlyphCount = 0;
1210 for (uint16_t y = 0; y < numGlyphs; ++y) {
1211 if (glyphIDs[y] >= data.lowerBounds && glyphIDs[y] < data.upperBounds) {
1212 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1213 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1214 &(pos[y * scalarsPerPos]),
1215 scalarsPerPos * sizeof(SkScalar));
1216 tmpGlyphCount++;
1217 }
1218 }
1219
1220 // recursively call this function with the right typeface
1221 SkPaint tmpPaint = paint;
1222 tmpPaint.setTypeface(data.typeface);
1223 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1224
1225 // turn off fallback chaining
1226 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1227 paintOpts.setUseFontFallbacks(false);
1228 tmpPaint.setPaintOptionsAndroid(paintOpts);
1229
1230 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1231 scalarsPerPos, tmpPaint);
1232 }
1233 return;
1234 }
1235#endif
1236
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001237 SkGlyphStorage storage(0);
1238 uint16_t* glyphIDs = NULL;
1239 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1240 &glyphIDs);
1241 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001242
1243 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001244 content.entry()->fContent.writeText("BT\n");
1245 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001246 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001247 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001248 uint16_t encodedValue = glyphIDs[i];
1249 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001250 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001251 i--;
1252 continue;
1253 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001254 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001255 SkScalar x = pos[i * scalarsPerPos];
1256 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001257 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001258 set_text_transform(x, y, textPaint.getTextSkewX(),
1259 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001260 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001261 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001262 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001263 content.entry()->fContent.writeText(encodedString.c_str());
1264 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001265 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001266 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001267}
1268
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001269void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001270 const SkPath& path, const SkMatrix* matrix,
1271 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001272 if (d.fClip->isEmpty()) {
1273 return;
1274 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001275 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001276}
1277
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001278void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001279 int vertexCount, const SkPoint verts[],
1280 const SkPoint texs[], const SkColor colors[],
1281 SkXfermode* xmode, const uint16_t indices[],
1282 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001283 if (d.fClip->isEmpty()) {
1284 return;
1285 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001286 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001287}
1288
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001289void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device, int x, int y,
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001290 const SkPaint& paint) {
1291 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1292 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001293 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001294 return;
1295 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001296
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001297 // Assume that a vector capable device means that it's a PDF Device.
1298 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001299 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001300 return;
1301 }
1302
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001303 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001304 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001305 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001306 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001307 return;
1308 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001309
1310 SkPDFFormXObject* xobject = new SkPDFFormXObject(pdfDevice);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001311 fXObjectResources.push(xobject); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001312 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001313 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001314
1315 // Merge glyph sets from the drawn device.
1316 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001317}
1318
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001319void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1320 INHERITED::onAttachToCanvas(canvas);
1321
1322 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1323 fClipStack = canvas->getClipStack();
1324}
1325
1326void SkPDFDevice::onDetachFromCanvas() {
1327 INHERITED::onDetachFromCanvas();
1328
1329 fClipStack = NULL;
1330}
1331
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001332ContentEntry* SkPDFDevice::getLastContentEntry() {
1333 if (fDrawingArea == kContent_DrawingArea) {
1334 return fLastContentEntry;
1335 } else {
1336 return fLastMarginContentEntry;
1337 }
1338}
1339
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001340SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001341 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001342 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001343 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001344 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001345 }
1346}
1347
1348void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1349 if (fDrawingArea == kContent_DrawingArea) {
1350 fLastContentEntry = contentEntry;
1351 } else {
1352 fLastMarginContentEntry = contentEntry;
1353 }
1354}
1355
1356void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001357 // A ScopedContentEntry only exists during the course of a draw call, so
1358 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001359 fDrawingArea = drawingArea;
1360}
1361
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001362SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001363 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001364 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001365
1366 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001367 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001368 fResourceDict->insertResourceAsReference(
1369 SkPDFResourceDict::kExtGState_ResourceType,
1370 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001371 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001372 }
1373
1374 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001375 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001376 fResourceDict->insertResourceAsReference(
1377 SkPDFResourceDict::kXObject_ResourceType,
1378 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001379 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001380 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001381
1382 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001383 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001384 fResourceDict->insertResourceAsReference(
1385 SkPDFResourceDict::kFont_ResourceType,
1386 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001387 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001388 }
1389
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001390 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001391 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001392 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001393 fResourceDict->insertResourceAsReference(
1394 SkPDFResourceDict::kPattern_ResourceType,
1395 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001396 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001397 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001398 }
1399 return fResourceDict;
1400}
1401
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001402const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1403 return fFontResources;
1404}
1405
reed@google.com2a006c12012-09-19 17:05:55 +00001406SkPDFArray* SkPDFDevice::copyMediaBox() const {
1407 // should this be a singleton?
1408 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001409
reed@google.com2a006c12012-09-19 17:05:55 +00001410 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001411 mediaBox->reserve(4);
1412 mediaBox->append(zero.get());
1413 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001414 mediaBox->appendInt(fPageSize.fWidth);
1415 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001416 return mediaBox;
1417}
1418
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001419SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001420 SkMemoryStream* result = new SkMemoryStream;
1421 result->setData(this->copyContentToData())->unref();
1422 return result;
1423}
1424
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001425void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1426 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001427 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1428 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001429 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001430 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001431 SkPoint translation;
1432 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001433 translation.negate();
1434 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1435 translation);
1436 gsState.updateMatrix(entry->fState.fMatrix);
1437 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001438
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001439 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001440 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001441 entry = entry->fNext.get();
1442 }
1443 gsState.drainStack();
1444}
1445
reed@google.com5667afc2011-06-27 14:42:15 +00001446SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001447 SkDynamicMemoryWStream data;
1448 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1449 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001450 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001451
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001452 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1453 // colors the contentArea white before it starts drawing into it and
1454 // that currently acts as our clip.
1455 // Also, think about adding a transform here (or assume that the values
1456 // sent across account for that)
1457 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001458
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001459 // If the content area is the entire page, then we don't need to clip
1460 // the content area (PDF area clips to the page size). Otherwise,
1461 // we have to clip to the content area; we've already applied the
1462 // initial transform, so just clip to the device size.
1463 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001464 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1465 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001466 emit_clip(NULL, &r, &data);
1467 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001468
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001469 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001470
reed@google.com5667afc2011-06-27 14:42:15 +00001471 // potentially we could cache this SkData, and only rebuild it if we
1472 // see that our state has changed.
1473 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001474}
1475
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001476#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001477/* Draws an inverse filled path by using Path Ops to compute the positive
1478 * inverse using the current clip as the inverse bounds.
1479 * Return true if this was an inverse path and was properly handled,
1480 * otherwise returns false and the normal drawing routine should continue,
1481 * either as a (incorrect) fallback or because the path was not inverse
1482 * in the first place.
1483 */
1484bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001485 const SkPaint& paint, bool pathIsMutable,
1486 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001487 if (!origPath.isInverseFillType()) {
1488 return false;
1489 }
1490
1491 if (d.fClip->isEmpty()) {
1492 return false;
1493 }
1494
1495 SkPath modifiedPath;
1496 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1497 SkPaint noInversePaint(paint);
1498
1499 // Merge stroking operations into final path.
1500 if (SkPaint::kStroke_Style == paint.getStyle() ||
1501 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1502 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1503 if (doFillPath) {
1504 noInversePaint.setStyle(SkPaint::kFill_Style);
1505 noInversePaint.setStrokeWidth(0);
1506 pathPtr = &modifiedPath;
1507 } else {
1508 // To be consistent with the raster output, hairline strokes
1509 // are rendered as non-inverted.
1510 modifiedPath.toggleInverseFillType();
1511 drawPath(d, modifiedPath, paint, NULL, true);
1512 return true;
1513 }
1514 }
1515
1516 // Get bounds of clip in current transform space
1517 // (clip bounds are given in device space).
1518 SkRect bounds;
1519 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001520 SkMatrix totalMatrix = *d.fMatrix;
1521 if (prePathMatrix) {
1522 totalMatrix.preConcat(*prePathMatrix);
1523 }
1524 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001525 return false;
1526 }
1527 bounds.set(d.fClip->getBounds());
1528 transformInverse.mapRect(&bounds);
1529
1530 // Extend the bounds by the line width (plus some padding)
1531 // so the edge doesn't cause a visible stroke.
1532 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1533 paint.getStrokeWidth() + SK_Scalar1);
1534
1535 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1536 return false;
1537 }
1538
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001539 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001540 return true;
1541}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001542#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001543
epoger@google.comb58772f2013-03-08 09:09:10 +00001544bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1545 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001546 SkAnnotation* annotationInfo = p.getAnnotation();
1547 if (!annotationInfo) {
1548 return false;
1549 }
1550 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001551 if (urlData) {
1552 handleLinkToURL(urlData, r, matrix);
1553 return p.isNoDrawAnnotation();
1554 }
1555 SkData* linkToName = annotationInfo->find(SkAnnotationKeys::Link_Named_Dest_Key());
1556 if (linkToName) {
1557 handleLinkToNamedDest(linkToName, r, matrix);
1558 return p.isNoDrawAnnotation();
1559 }
1560 return false;
1561}
1562
1563bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1564 const SkMatrix& matrix,
1565 const SkPaint& paint) {
1566 SkAnnotation* annotationInfo = paint.getAnnotation();
1567 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001568 return false;
1569 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001570 SkData* nameData = annotationInfo->find(SkAnnotationKeys::Define_Named_Dest_Key());
1571 if (nameData) {
1572 for (size_t i = 0; i < count; i++) {
1573 defineNamedDestination(nameData, points[i], matrix);
1574 }
1575 return paint.isNoDrawAnnotation();
1576 }
1577 return false;
1578}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001579
epoger@google.comb58772f2013-03-08 09:09:10 +00001580SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r, const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001581 SkMatrix transform = matrix;
1582 transform.postConcat(fInitialTransform);
1583 SkRect translatedRect;
1584 transform.mapRect(&translatedRect, r);
1585
reed@google.com2a006c12012-09-19 17:05:55 +00001586 if (NULL == fAnnotations) {
1587 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001588 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001589 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001590 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001591 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001592
epoger@google.comb58772f2013-03-08 09:09:10 +00001593 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001594 border->reserve(3);
1595 border->appendInt(0); // Horizontal corner radius.
1596 border->appendInt(0); // Vertical corner radius.
1597 border->appendInt(0); // Width, 0 = no border.
1598 annotation->insert("Border", border.get());
1599
epoger@google.comb58772f2013-03-08 09:09:10 +00001600 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001601 rect->reserve(4);
1602 rect->appendScalar(translatedRect.fLeft);
1603 rect->appendScalar(translatedRect.fTop);
1604 rect->appendScalar(translatedRect.fRight);
1605 rect->appendScalar(translatedRect.fBottom);
1606 annotation->insert("Rect", rect.get());
1607
epoger@google.comb58772f2013-03-08 09:09:10 +00001608 return annotation;
1609}
epoger@google.com1cad8982013-03-06 00:05:13 +00001610
epoger@google.comb58772f2013-03-08 09:09:10 +00001611void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1612 const SkMatrix& matrix) {
1613 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1614
1615 SkString url(static_cast<const char *>(urlData->data()),
1616 urlData->size() - 1);
1617 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1618 action->insertName("S", "URI");
1619 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1620 annotation->insert("A", action.get());
1621}
1622
1623void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1624 const SkMatrix& matrix) {
1625 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1626 SkString name(static_cast<const char *>(nameData->data()),
1627 nameData->size() - 1);
1628 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1629}
1630
1631struct NamedDestination {
1632 const SkData* nameData;
1633 SkPoint point;
1634
1635 NamedDestination(const SkData* nameData, const SkPoint& point)
1636 : nameData(nameData), point(point) {
1637 nameData->ref();
1638 }
1639
1640 ~NamedDestination() {
1641 nameData->unref();
1642 }
1643};
1644
1645void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1646 const SkMatrix& matrix) {
1647 SkMatrix transform = matrix;
1648 transform.postConcat(fInitialTransform);
1649 SkPoint translatedPoint;
1650 transform.mapXY(point.x(), point.y(), &translatedPoint);
1651 fNamedDestinations.push(
1652 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1653}
1654
1655void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1656 int nDest = fNamedDestinations.count();
1657 for (int i = 0; i < nDest; i++) {
1658 NamedDestination* dest = fNamedDestinations[i];
1659 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1660 pdfDest->reserve(5);
1661 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1662 pdfDest->appendName("XYZ");
1663 pdfDest->appendScalar(dest->point.x());
1664 pdfDest->appendScalar(dest->point.y());
1665 pdfDest->appendInt(0); // Leave zoom unchanged
1666 dict->insert(static_cast<const char *>(dest->nameData->data()), pdfDest);
1667 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001668}
1669
reed@google.comfc641d02012-09-20 17:52:20 +00001670SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1671 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001672 // We always draw the form xobjects that we create back into the device, so
1673 // we simply preserve the font usage instead of pulling it out and merging
1674 // it back in later.
1675 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001676 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001677 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001678}
1679
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001680void SkPDFDevice::clearClipFromContent(const SkClipStack* clipStack,
1681 const SkRegion& clipRegion) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001682 if (clipRegion.isEmpty() || isContentEmpty()) {
1683 return;
1684 }
reed@google.comfc641d02012-09-20 17:52:20 +00001685 SkAutoTUnref<SkPDFFormXObject> curContent(createFormXObjectFromDevice());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001686
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001687 // Redraw what we already had, but with the clip as a mask.
reed@google.comfc641d02012-09-20 17:52:20 +00001688 drawFormXObjectWithClip(curContent, clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001689}
1690
1691void SkPDFDevice::drawFormXObjectWithClip(SkPDFFormXObject* xobject,
1692 const SkClipStack* clipStack,
1693 const SkRegion& clipRegion,
1694 bool invertClip) {
1695 if (clipRegion.isEmpty() && !invertClip) {
1696 return;
1697 }
1698
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001699 // Create the mask.
1700 SkMatrix identity;
1701 identity.reset();
1702 SkDraw draw;
1703 draw.fMatrix = &identity;
1704 draw.fClip = &clipRegion;
1705 draw.fClipStack = clipStack;
1706 SkPaint stockPaint;
1707 this->drawPaint(draw, stockPaint);
reed@google.comfc641d02012-09-20 17:52:20 +00001708 SkAutoTUnref<SkPDFFormXObject> maskFormXObject(createFormXObjectFromDevice());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001709 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001710 SkPDFGraphicState::GetSMaskGraphicState(maskFormXObject, invertClip,
1711 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001712
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001713 // Draw the xobject with the clip as a mask.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001714 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001715 identity, stockPaint);
1716 if (!content.entry()) {
1717 return;
1718 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001719 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001720 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001721 SkPDFUtils::DrawFormXObject(fXObjectResources.count(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001722 &content.entry()->fContent);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001723 fXObjectResources.push(xobject);
1724 xobject->ref();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001725
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001726 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001727 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001728 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001729}
1730
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001731ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1732 const SkRegion& clipRegion,
1733 const SkMatrix& matrix,
1734 const SkPaint& paint,
1735 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001736 SkPDFFormXObject** dst) {
1737 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001738 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001739 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001740 }
1741
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001742 // The clip stack can come from an SkDraw where it is technically optional.
1743 SkClipStack synthesizedClipStack;
1744 if (clipStack == NULL) {
1745 if (clipRegion == fExistingClipRegion) {
1746 clipStack = &fExistingClipStack;
1747 } else {
1748 // GraphicStackState::updateClip expects the clip stack to have
1749 // fExistingClip as a prefix, so start there, then set the clip
1750 // to the passed region.
1751 synthesizedClipStack = fExistingClipStack;
1752 SkPath clipPath;
1753 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001754 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1755 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001756 clipStack = &synthesizedClipStack;
1757 }
1758 }
1759
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001760 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1761 if (paint.getXfermode()) {
1762 paint.getXfermode()->asMode(&xfermode);
1763 }
1764
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001765 if (xfermode == SkXfermode::kClear_Mode ||
1766 xfermode == SkXfermode::kSrc_Mode) {
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001767 this->clearClipFromContent(clipStack, clipRegion);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001768 } else if (xfermode == SkXfermode::kSrcIn_Mode ||
1769 xfermode == SkXfermode::kDstIn_Mode ||
1770 xfermode == SkXfermode::kSrcOut_Mode ||
1771 xfermode == SkXfermode::kDstOut_Mode) {
1772 // For the following modes, we use both source and destination, but
1773 // we use one as a smask for the other, so we have to make form xobjects
1774 // out of both of them: SrcIn, DstIn, SrcOut, DstOut.
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001775 if (isContentEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001776 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001777 } else {
reed@google.comfc641d02012-09-20 17:52:20 +00001778 *dst = createFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001779 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001780 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001781 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001782 // SrcAtop, DestAtop, Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001783
1784 // These xfer modes don't draw source at all.
1785 if (xfermode == SkXfermode::kClear_Mode ||
1786 xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001787 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001788 }
1789
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001790 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001791 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001792
1793 ContentEntry* lastContentEntry = getLastContentEntry();
1794 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1795 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001796 } else {
1797 newEntry.reset(new ContentEntry);
1798 entry = newEntry.get();
1799 }
1800
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001801 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001802 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001803 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1804 entry->fState.compareInitialState(lastContentEntry->fState)) {
1805 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001806 }
1807
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001808 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001809 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001810 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001811 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001812 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001813 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001814 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001815 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001816 lastContentEntry->fNext.reset(entry);
1817 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001818 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001819 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001820 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001821}
1822
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001823void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
1824 SkPDFFormXObject* dst) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001825 if (xfermode != SkXfermode::kSrcIn_Mode &&
1826 xfermode != SkXfermode::kDstIn_Mode &&
1827 xfermode != SkXfermode::kSrcOut_Mode &&
1828 xfermode != SkXfermode::kDstOut_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001829 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001830 return;
1831 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001832
1833 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001834 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001835 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001836 // We have to make a copy of these here because changing the current
1837 // content into a form xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001838 SkClipStack clipStack = contentEntries->fState.fClipStack;
1839 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001840
reed@google.comfc641d02012-09-20 17:52:20 +00001841 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001842 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001843 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001844 }
1845
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001846 drawFormXObjectWithClip(dst, &clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001847
1848 // We've redrawn dst minus the clip area, if there's no src, we're done.
1849 if (!srcFormXObject.get()) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001850 return;
1851 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001852
1853 SkMatrix identity;
1854 identity.reset();
1855 SkPaint stockPaint;
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001856 ScopedContentEntry inClipContentEntry(this, &fExistingClipStack,
1857 fExistingClipRegion, identity,
1858 stockPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001859 if (!inClipContentEntry.entry()) {
1860 return;
1861 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001862
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001863 SkAutoTUnref<SkPDFGraphicState> sMaskGS;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001864 if (xfermode == SkXfermode::kSrcIn_Mode ||
1865 xfermode == SkXfermode::kSrcOut_Mode) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001866 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001867 dst,
1868 xfermode == SkXfermode::kSrcOut_Mode,
1869 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001870 fXObjectResources.push(srcFormXObject.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001871 srcFormXObject.get()->ref();
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001872 } else {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001873 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001874 srcFormXObject.get(),
1875 xfermode == SkXfermode::kDstOut_Mode,
1876 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001877 // dst already added to fXObjectResources in drawFormXObjectWithClip.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001878 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001879 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001880 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001881
1882 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001883 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001884
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001885 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001886 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001887 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001888}
1889
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001890bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001891 ContentEntry* contentEntries = getContentEntries()->get();
1892 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1893 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001894 return true;
1895 }
1896 return false;
1897}
1898
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001899void SkPDFDevice::populateGraphicStateEntryFromPaint(
1900 const SkMatrix& matrix,
1901 const SkClipStack& clipStack,
1902 const SkRegion& clipRegion,
1903 const SkPaint& paint,
1904 bool hasText,
1905 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001906 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001907
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001908 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1909 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001910
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001911 entry->fMatrix = matrix;
1912 entry->fClipStack = clipStack;
1913 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001914 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1915 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001916
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001917 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001918 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001919 const SkShader* shader = paint.getShader();
1920 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001921 if (shader) {
1922 // PDF positions patterns relative to the initial transform, so
1923 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001924 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001925 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001926
1927 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001928 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001929 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001930
1931 // We need to apply the initial transform to bounds in order to get
1932 // bounds in a consistent coordinate system.
1933 SkRect boundsTemp;
1934 boundsTemp.set(bounds);
1935 fInitialTransform.mapRect(&boundsTemp);
1936 boundsTemp.roundOut(&bounds);
1937
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001938 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001939
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001940 if (pdfShader.get()) {
1941 // pdfShader has been canonicalized so we can directly compare
1942 // pointers.
1943 int resourceIndex = fShaderResources.find(pdfShader.get());
1944 if (resourceIndex < 0) {
1945 resourceIndex = fShaderResources.count();
1946 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001947 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001948 }
1949 entry->fShaderIndex = resourceIndex;
1950 } else {
1951 // A color shader is treated as an invalid shader so we don't have
1952 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001953 SkShader::GradientInfo gradientInfo;
1954 SkColor gradientColor;
1955 gradientInfo.fColors = &gradientColor;
1956 gradientInfo.fColorOffsets = NULL;
1957 gradientInfo.fColorCount = 1;
1958 if (shader->asAGradient(&gradientInfo) ==
1959 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001960 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1961 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001962 }
1963 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001964 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001965
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001966 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001967 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001968 newGraphicState.reset(
1969 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001970 } else {
1971 SkPaint newPaint = paint;
1972 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001973 newGraphicState.reset(
1974 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001975 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001976 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001977 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001978
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001979 if (hasText) {
1980 entry->fTextScaleX = paint.getTextScaleX();
1981 entry->fTextFill = paint.getStyle();
1982 } else {
1983 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001984 }
1985}
1986
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001987int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
1988 // Assumes that gs has been canonicalized (so we can directly compare
1989 // pointers).
1990 int result = fGraphicStateResources.find(gs);
1991 if (result < 0) {
1992 result = fGraphicStateResources.count();
1993 fGraphicStateResources.push(gs);
1994 gs->ref();
1995 }
1996 return result;
1997}
1998
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001999void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2000 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002001 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002002 if (contentEntry->fState.fFont == NULL ||
2003 contentEntry->fState.fTextSize != paint.getTextSize() ||
2004 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002005 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002006 contentEntry->fContent.writeText("/");
2007 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2008 SkPDFResourceDict::kFont_ResourceType,
2009 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002010 contentEntry->fContent.writeText(" ");
2011 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2012 contentEntry->fContent.writeText(" Tf\n");
2013 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002014 }
2015}
2016
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002017int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002018 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002019 int resourceIndex = fFontResources.find(newFont.get());
2020 if (resourceIndex < 0) {
2021 resourceIndex = fFontResources.count();
2022 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002023 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002024 }
2025 return resourceIndex;
2026}
2027
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002028void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002029 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002030 const SkRegion& origClipRegion,
2031 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002032 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002033 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002034 SkMatrix matrix = origMatrix;
2035 SkRegion perspectiveBounds;
2036 const SkRegion* clipRegion = &origClipRegion;
2037 SkBitmap perspectiveBitmap;
2038 const SkBitmap* bitmap = &origBitmap;
2039 SkBitmap tmpSubsetBitmap;
2040
2041 // Rasterize the bitmap using perspective in a new bitmap.
2042 if (origMatrix.hasPerspective()) {
2043 SkBitmap* subsetBitmap;
2044 if (srcRect) {
2045 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2046 return;
2047 }
2048 subsetBitmap = &tmpSubsetBitmap;
2049 } else {
2050 subsetBitmap = &tmpSubsetBitmap;
2051 *subsetBitmap = origBitmap;
2052 }
2053 srcRect = NULL;
2054
2055 // Transform the bitmap in the new space.
2056 SkPath perspectiveOutline;
2057 perspectiveOutline.addRect(
2058 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2059 SkIntToScalar(subsetBitmap->height())));
2060 perspectiveOutline.transform(origMatrix);
2061
2062 // TODO(edisonn): perf - use current clip too.
2063 // Retrieve the bounds of the new shape.
2064 SkRect bounds = perspectiveOutline.getBounds();
2065
2066 // TODO(edisonn): add DPI settings. Currently 1 pixel/point, which does
2067 // not look great, but it is not producing large PDFs.
2068
2069 // TODO(edisonn): A better approach would be to use a bitmap shader
2070 // (in clamp mode) and draw a rect over the entire bounding box. Then
2071 // intersect perspectiveOutline to the clip. That will avoid introducing
2072 // alpha to the image while still giving good behavior at the edge of
2073 // the image. Avoiding alpha will reduce the pdf size and generation
2074 // CPU time some.
2075
2076 perspectiveBitmap.setConfig(SkBitmap::kARGB_8888_Config,
2077 SkScalarCeilToInt(bounds.width()),
2078 SkScalarCeilToInt(bounds.height()));
2079 perspectiveBitmap.allocPixels();
2080 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2081
2082 SkBitmapDevice device(perspectiveBitmap);
2083 SkCanvas canvas(&device);
2084
2085 SkScalar deltaX = bounds.left();
2086 SkScalar deltaY = bounds.top();
2087
2088 SkMatrix offsetMatrix = origMatrix;
2089 offsetMatrix.postTranslate(-deltaX, -deltaY);
2090
2091 // Translate the draw in the new canvas, so we perfectly fit the
2092 // shape in the bitmap.
2093 canvas.setMatrix(offsetMatrix);
2094
2095 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2096
2097 // Make sure the final bits are in the bitmap.
2098 canvas.flush();
2099
2100 // In the new space, we use the identity matrix translated.
2101 matrix.setTranslate(deltaX, deltaY);
2102 perspectiveBounds.setRect(
2103 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2104 SkScalarFloorToInt(bounds.y()),
2105 SkScalarCeilToInt(bounds.width()),
2106 SkScalarCeilToInt(bounds.height())));
2107 clipRegion = &perspectiveBounds;
2108 srcRect = NULL;
2109 bitmap = &perspectiveBitmap;
2110 }
2111
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002112 SkMatrix scaled;
2113 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002114 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2115 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002116 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002117 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002118 scaled.postScale(SkIntToScalar(subset.width()),
2119 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002120 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002121 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002122 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002123 return;
2124 }
2125
2126 if (srcRect && !subset.intersect(*srcRect)) {
2127 return;
2128 }
2129
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002130 SkPDFImage* image = SkPDFImage::CreateImage(*bitmap, subset, fEncoder);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002131 if (!image) {
2132 return;
2133 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002134
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002135 fXObjectResources.push(image); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002136 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002137 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002138}
reed@google.com982cb872011-12-07 18:34:08 +00002139
2140bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2141 SkCanvas::Config8888) {
2142 return false;
2143}
reed@google.comb55deeb2012-01-06 14:43:09 +00002144
2145bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2146 return false;
2147}