blob: e3134f4ac397ddac9faf50f518a40fe53e74e7db [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;
vandebo@chromium.orgeb5992c2013-10-18 20:14:08 +0000651 // Shape has to be flatten before we get here.
652 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000653 if (paint.getXfermode()) {
654 paint.getXfermode()->asMode(&fXfermode);
655 }
656 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
657 matrix, paint, hasText,
658 &fDstFormXObject);
659 }
660};
661
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000662////////////////////////////////////////////////////////////////////////////////
663
ctguil@chromium.org15261292011-04-29 17:54:16 +0000664static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000665 const SkMatrix* initialTransform) {
reed@android.comf2b98d62010-12-20 18:26:13 +0000666 SkBitmap bitmap;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000667 if (initialTransform) {
668 // Compute the size of the drawing area.
669 SkVector drawingSize;
670 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000671 drawingSize.set(SkIntToScalar(contentSize.fWidth),
672 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000673 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000674 // This shouldn't happen, initial transform should be invertible.
675 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000676 inverse.reset();
677 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000678 inverse.mapVectors(&drawingSize, 1);
679 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
680 bitmap.setConfig(SkBitmap::kNo_Config, abs(size.fWidth),
681 abs(size.fHeight));
682 } else {
683 bitmap.setConfig(SkBitmap::kNo_Config, abs(contentSize.fWidth),
684 abs(contentSize.fHeight));
685 }
686
reed@android.comf2b98d62010-12-20 18:26:13 +0000687 return bitmap;
688}
689
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000690// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000691SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000692 const SkMatrix& initialTransform)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000693 : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
ctguil@chromium.org15261292011-04-29 17:54:16 +0000694 fPageSize(pageSize),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000695 fContentSize(contentSize),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000696 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000697 fLastMarginContentEntry(NULL),
edisonn@google.comd9dfa182013-04-24 13:01:01 +0000698 fClipStack(NULL),
699 fEncoder(NULL) {
vandebo@chromium.orgeb5992c2013-10-18 20:14:08 +0000700 // Just report that PDF does not supports perspective in the
701 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000702 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
703
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000704 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000705 // origin at the bottom left. This matrix corrects for that. But that only
706 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000707 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
708 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000709 fInitialTransform.preConcat(initialTransform);
710
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000711 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000712 fExistingClipRegion.setRect(existingClip);
713
714 this->init();
715}
716
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000717// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000718SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
719 const SkClipStack& existingClipStack,
720 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000721 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000722 fPageSize(layerSize),
723 fContentSize(layerSize),
724 fExistingClipStack(existingClipStack),
725 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000726 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000727 fLastMarginContentEntry(NULL),
728 fClipStack(NULL) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000729 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000730 this->init();
731}
732
733SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000734 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000735}
736
737void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000738 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000739 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000740 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000741 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000742 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000743 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000744 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000745 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000746 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
747 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000748}
749
vandebo@chromium.org98594282011-07-25 22:34:12 +0000750void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000751 fGraphicStateResources.unrefAll();
752 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000753 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000754 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000755 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000756 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000757 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000758
vandebo@chromium.org98594282011-07-25 22:34:12 +0000759 if (clearFontUsage) {
760 fFontGlyphUsage->reset();
761 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000762}
763
reed@google.com982cb872011-12-07 18:34:08 +0000764uint32_t SkPDFDevice::getDeviceCapabilities() {
765 return kVector_Capability;
766}
767
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000768void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000769 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000770 this->init();
771
772 SkPaint paint;
773 paint.setColor(color);
774 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000775 SkMatrix identity;
776 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000777 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
778 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000779 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000780}
781
782void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000783 SkPaint newPaint = paint;
784 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000785 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000786 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000787}
788
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000789void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
790 ContentEntry* contentEntry) {
791 if (!contentEntry) {
792 return;
793 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000794 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
795 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000796 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000797 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000798 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000799 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000800 inverse.mapRect(&bbox);
801
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000802 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000803 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000804 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000805}
806
807void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
808 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000809 const SkPaint& passedPaint) {
810 if (count == 0) {
811 return;
812 }
813
epoger@google.comb58772f2013-03-08 09:09:10 +0000814 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
815 return;
816 }
817
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000818 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
819 // We only use this when there's a path effect because of the overhead
820 // of multiple calls to setUpContentEntry it causes.
821 if (passedPaint.getPathEffect()) {
822 if (d.fClip->isEmpty()) {
823 return;
824 }
825 SkDraw pointDraw(d);
826 pointDraw.fDevice = this;
827 pointDraw.drawPoints(mode, count, points, passedPaint, true);
828 return;
829 }
830
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000831 const SkPaint* paint = &passedPaint;
832 SkPaint modifiedPaint;
833
834 if (mode == SkCanvas::kPoints_PointMode &&
835 paint->getStrokeCap() != SkPaint::kRound_Cap) {
836 modifiedPaint = *paint;
837 paint = &modifiedPaint;
838 if (paint->getStrokeWidth()) {
839 // PDF won't draw a single point with square/butt caps because the
840 // orientation is ambiguous. Draw a rectangle instead.
841 modifiedPaint.setStyle(SkPaint::kFill_Style);
842 SkScalar strokeWidth = paint->getStrokeWidth();
843 SkScalar halfStroke = SkScalarHalf(strokeWidth);
844 for (size_t i = 0; i < count; i++) {
845 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
846 r.inset(-halfStroke, -halfStroke);
847 drawRect(d, r, modifiedPaint);
848 }
849 return;
850 } else {
851 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
852 }
853 }
854
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000855 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000856 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000857 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000858 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000859
860 switch (mode) {
861 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000862 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000863 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000864 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000865 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000866 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000867 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000868 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000869 break;
870 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000871 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000872 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000873 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000874 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000875 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000876 &content.entry()->fContent);
877 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000878 }
879 break;
880 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000881 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
882 for (size_t i = 0; i < count; i++) {
883 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000884 &content.entry()->fContent);
885 SkPDFUtils::ClosePath(&content.entry()->fContent);
886 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000887 }
888 break;
889 default:
890 SkASSERT(false);
891 }
892}
893
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000894void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000895 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000896 SkRect r = rect;
897 r.sort();
898
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000899 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000900 if (d.fClip->isEmpty()) {
901 return;
902 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000903 SkPath path;
904 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000905 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000906 return;
907 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000908
epoger@google.comb58772f2013-03-08 09:09:10 +0000909 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000910 return;
911 }
912
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000913 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000914 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000915 return;
916 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000917 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000918 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000919 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000920}
921
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000922void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000923 const SkPaint& paint, const SkMatrix* prePathMatrix,
924 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000925 SkPath modifiedPath;
926 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
927
928 SkMatrix matrix = *d.fMatrix;
929 if (prePathMatrix) {
930 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
931 if (!pathIsMutable) {
932 pathPtr = &modifiedPath;
933 pathIsMutable = true;
934 }
935 origPath.transform(*prePathMatrix, pathPtr);
936 } else {
937 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000938 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000939 return;
940 }
941 }
942 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000943
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000944 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000945 if (d.fClip->isEmpty()) {
946 return;
947 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000948 if (!pathIsMutable) {
949 pathPtr = &modifiedPath;
950 pathIsMutable = true;
951 }
952 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000953
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000954 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000955 noEffectPaint.setPathEffect(NULL);
956 if (fill) {
957 noEffectPaint.setStyle(SkPaint::kFill_Style);
958 } else {
959 noEffectPaint.setStyle(SkPaint::kStroke_Style);
960 noEffectPaint.setStrokeWidth(0);
961 }
962 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000963 return;
964 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000965
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000966#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000967 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000968 return;
969 }
970#endif
971
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000972 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000973 return;
974 }
975
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000976 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000977 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000978 return;
979 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000980 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
981 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000982 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000983 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000984}
985
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000986void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
987 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000988 const SkPaint& paint,
989 SkCanvas::DrawBitmapRectFlags flags) {
990 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000991 SkMatrix matrix;
992 SkRect bitmapBounds, tmpSrc, tmpDst;
993 SkBitmap tmpBitmap;
994
995 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
996
997 // Compute matrix from the two rectangles
998 if (src) {
999 tmpSrc = *src;
1000 } else {
1001 tmpSrc = bitmapBounds;
1002 }
1003 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1004
1005 const SkBitmap* bitmapPtr = &bitmap;
1006
1007 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1008 // needed (if the src was clipped). No check needed if src==null.
1009 if (src) {
1010 if (!bitmapBounds.contains(*src)) {
1011 if (!tmpSrc.intersect(bitmapBounds)) {
1012 return; // nothing to draw
1013 }
1014 // recompute dst, based on the smaller tmpSrc
1015 matrix.mapRect(&tmpDst, tmpSrc);
1016 }
1017
1018 // since we may need to clamp to the borders of the src rect within
1019 // the bitmap, we extract a subset.
1020 // TODO: make sure this is handled in drawBitmap and remove from here.
1021 SkIRect srcIR;
1022 tmpSrc.roundOut(&srcIR);
1023 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1024 return;
1025 }
1026 bitmapPtr = &tmpBitmap;
1027
1028 // Since we did an extract, we need to adjust the matrix accordingly
1029 SkScalar dx = 0, dy = 0;
1030 if (srcIR.fLeft > 0) {
1031 dx = SkIntToScalar(srcIR.fLeft);
1032 }
1033 if (srcIR.fTop > 0) {
1034 dy = SkIntToScalar(srcIR.fTop);
1035 }
1036 if (dx || dy) {
1037 matrix.preTranslate(dx, dy);
1038 }
1039 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001040 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001041}
1042
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001043void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001044 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001045 if (d.fClip->isEmpty()) {
1046 return;
1047 }
1048
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001049 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001050 transform.postConcat(*d.fMatrix);
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001051 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001052}
1053
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001054void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001055 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001056 if (d.fClip->isEmpty()) {
1057 return;
1058 }
1059
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001060 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001061 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001062 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001063}
1064
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001065void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001066 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001067 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1068 if (paint.getMaskFilter() != NULL) {
1069 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1070 // making text unreadable (e.g. same text twice when using CSS shadows).
1071 return;
1072 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001073 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001074 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001075 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001076 return;
1077 }
1078
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001079 SkGlyphStorage storage(0);
1080 uint16_t* glyphIDs = NULL;
1081 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1082 &glyphIDs);
1083 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001084
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001085 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001086 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001087 content.entry()->fContent.writeText("BT\n");
1088 set_text_transform(x, y, textPaint.getTextSkewX(),
1089 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001090 size_t consumedGlyphCount = 0;
1091 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001092 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1093 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001094 size_t availableGlyphs =
1095 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1096 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001097 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1098 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001099 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001100 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001101 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001102 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001103 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001104 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001105 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001106 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001107}
1108
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001109void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001110 const SkScalar pos[], SkScalar constY,
1111 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001112 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1113 if (paint.getMaskFilter() != NULL) {
1114 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1115 // making text unreadable (e.g. same text twice when using CSS shadows).
1116 return;
1117 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001118 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001119 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001120 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001121 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001122 return;
1123 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001124
djsollen@google.com5df5e612013-10-03 14:42:24 +00001125#ifdef SK_BUILD_FOR_ANDROID
1126 /*
1127 * In the case that we have enabled fallback fonts on Android we need to
1128 * take the following steps to ensure that the PDF draws all characters,
1129 * regardless of their underlying font file, correctly.
1130 *
1131 * 1. Convert input into GlyphID encoding if it currently is not
1132 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1133 * glyph resolves to
1134 * 3. Iterate over those typefaces and recursively call this function with
1135 * only the glyphs (and their positions) that the typeface is capable of
1136 * resolving.
1137 */
1138 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1139 uint16_t* glyphIDs = NULL;
1140 SkGlyphStorage tmpStorage(0);
1141 size_t numGlyphs = 0;
1142
1143 // convert to glyphIDs
1144 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1145 numGlyphs = len / 2;
1146 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1147 } else {
1148 numGlyphs = paint.textToGlyphs(text, len, NULL);
1149 tmpStorage.reset(numGlyphs);
1150 paint.textToGlyphs(text, len, tmpStorage.get());
1151 glyphIDs = tmpStorage.get();
1152 }
1153
1154 // if no typeface is provided in the paint get the default
1155 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1156 if (NULL == origFace.get()) {
1157 origFace.reset(SkTypeface::RefDefault());
1158 }
1159 const uint16_t origGlyphCount = origFace->countGlyphs();
1160
1161 // keep a list of the already visited typefaces and some data about them
1162 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1163
1164 // find all the typefaces needed to resolve this run of text
1165 bool usesOriginalTypeface = false;
1166 for (uint16_t x = 0; x < numGlyphs; ++x) {
1167 // optimization that checks to see if original typeface can resolve the glyph
1168 if (glyphIDs[x] < origGlyphCount) {
1169 usesOriginalTypeface = true;
1170 continue;
1171 }
1172
1173 // find the fallback typeface that supports this glyph
1174 TypefaceFallbackData data;
1175 data.typeface = SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1176 paint.getPaintOptionsAndroid(),
1177 &data.lowerBounds, &data.upperBounds);
1178 // add the typeface and its data if we don't have it
1179 if (data.typeface && !visitedTypefaces.contains(data)) {
1180 visitedTypefaces.push(data);
1181 }
1182 }
1183
1184 // if the original font was used then add it to the list as well
1185 if (usesOriginalTypeface) {
1186 TypefaceFallbackData* data = visitedTypefaces.push();
1187 data->typeface = origFace.get();
1188 data->lowerBounds = 0;
1189 data->upperBounds = origGlyphCount;
1190 }
1191
1192 // keep a scratch glyph and pos storage
1193 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1194 SkScalar* tmpPos = posStorage.get();
1195 SkGlyphStorage glyphStorage(numGlyphs);
1196 uint16_t* tmpGlyphIDs = glyphStorage.get();
1197
1198 // loop through all the valid typefaces, trim the glyphs to only those
1199 // resolved by the typeface, and then draw that run of glyphs
1200 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1201 const TypefaceFallbackData& data = visitedTypefaces[x];
1202
1203 int tmpGlyphCount = 0;
1204 for (uint16_t y = 0; y < numGlyphs; ++y) {
1205 if (glyphIDs[y] >= data.lowerBounds && glyphIDs[y] < data.upperBounds) {
1206 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1207 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1208 &(pos[y * scalarsPerPos]),
1209 scalarsPerPos * sizeof(SkScalar));
1210 tmpGlyphCount++;
1211 }
1212 }
1213
1214 // recursively call this function with the right typeface
1215 SkPaint tmpPaint = paint;
1216 tmpPaint.setTypeface(data.typeface);
1217 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1218
1219 // turn off fallback chaining
1220 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1221 paintOpts.setUseFontFallbacks(false);
1222 tmpPaint.setPaintOptionsAndroid(paintOpts);
1223
1224 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1225 scalarsPerPos, tmpPaint);
1226 }
1227 return;
1228 }
1229#endif
1230
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001231 SkGlyphStorage storage(0);
1232 uint16_t* glyphIDs = NULL;
1233 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1234 &glyphIDs);
1235 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001236
1237 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001238 content.entry()->fContent.writeText("BT\n");
1239 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001240 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001241 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001242 uint16_t encodedValue = glyphIDs[i];
1243 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001244 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001245 i--;
1246 continue;
1247 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001248 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001249 SkScalar x = pos[i * scalarsPerPos];
1250 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001251 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001252 set_text_transform(x, y, textPaint.getTextSkewX(),
1253 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001254 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001255 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001256 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001257 content.entry()->fContent.writeText(encodedString.c_str());
1258 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001259 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001260 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001261}
1262
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001263void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001264 const SkPath& path, const SkMatrix* matrix,
1265 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001266 if (d.fClip->isEmpty()) {
1267 return;
1268 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001269 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001270}
1271
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001272void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001273 int vertexCount, const SkPoint verts[],
1274 const SkPoint texs[], const SkColor colors[],
1275 SkXfermode* xmode, const uint16_t indices[],
1276 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001277 if (d.fClip->isEmpty()) {
1278 return;
1279 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001280 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001281}
1282
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001283void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device, int x, int y,
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001284 const SkPaint& paint) {
1285 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1286 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001287 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001288 return;
1289 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001290
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001291 // Assume that a vector capable device means that it's a PDF Device.
1292 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001293 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001294 return;
1295 }
1296
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001297 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001298 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001299 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001300 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001301 return;
1302 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001303
1304 SkPDFFormXObject* xobject = new SkPDFFormXObject(pdfDevice);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001305 fXObjectResources.push(xobject); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001306 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001307 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001308
1309 // Merge glyph sets from the drawn device.
1310 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001311}
1312
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001313void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1314 INHERITED::onAttachToCanvas(canvas);
1315
1316 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1317 fClipStack = canvas->getClipStack();
1318}
1319
1320void SkPDFDevice::onDetachFromCanvas() {
1321 INHERITED::onDetachFromCanvas();
1322
1323 fClipStack = NULL;
1324}
1325
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001326ContentEntry* SkPDFDevice::getLastContentEntry() {
1327 if (fDrawingArea == kContent_DrawingArea) {
1328 return fLastContentEntry;
1329 } else {
1330 return fLastMarginContentEntry;
1331 }
1332}
1333
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001334SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001335 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001336 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001337 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001338 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001339 }
1340}
1341
1342void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1343 if (fDrawingArea == kContent_DrawingArea) {
1344 fLastContentEntry = contentEntry;
1345 } else {
1346 fLastMarginContentEntry = contentEntry;
1347 }
1348}
1349
1350void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001351 // A ScopedContentEntry only exists during the course of a draw call, so
1352 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001353 fDrawingArea = drawingArea;
1354}
1355
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001356SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001357 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001358 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001359
1360 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001361 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001362 fResourceDict->insertResourceAsReference(
1363 SkPDFResourceDict::kExtGState_ResourceType,
1364 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001365 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001366 }
1367
1368 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001369 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001370 fResourceDict->insertResourceAsReference(
1371 SkPDFResourceDict::kXObject_ResourceType,
1372 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001373 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001374 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001375
1376 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001377 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001378 fResourceDict->insertResourceAsReference(
1379 SkPDFResourceDict::kFont_ResourceType,
1380 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001381 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001382 }
1383
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001384 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001385 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001386 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001387 fResourceDict->insertResourceAsReference(
1388 SkPDFResourceDict::kPattern_ResourceType,
1389 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001390 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001391 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001392 }
1393 return fResourceDict;
1394}
1395
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001396const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1397 return fFontResources;
1398}
1399
reed@google.com2a006c12012-09-19 17:05:55 +00001400SkPDFArray* SkPDFDevice::copyMediaBox() const {
1401 // should this be a singleton?
1402 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001403
reed@google.com2a006c12012-09-19 17:05:55 +00001404 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001405 mediaBox->reserve(4);
1406 mediaBox->append(zero.get());
1407 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001408 mediaBox->appendInt(fPageSize.fWidth);
1409 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001410 return mediaBox;
1411}
1412
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001413SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001414 SkMemoryStream* result = new SkMemoryStream;
1415 result->setData(this->copyContentToData())->unref();
1416 return result;
1417}
1418
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001419void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1420 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001421 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1422 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001423 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001424 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001425 SkPoint translation;
1426 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001427 translation.negate();
1428 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1429 translation);
1430 gsState.updateMatrix(entry->fState.fMatrix);
1431 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001432
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001433 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001434 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001435 entry = entry->fNext.get();
1436 }
1437 gsState.drainStack();
1438}
1439
reed@google.com5667afc2011-06-27 14:42:15 +00001440SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001441 SkDynamicMemoryWStream data;
1442 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1443 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001444 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001445
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001446 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1447 // colors the contentArea white before it starts drawing into it and
1448 // that currently acts as our clip.
1449 // Also, think about adding a transform here (or assume that the values
1450 // sent across account for that)
1451 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001452
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001453 // If the content area is the entire page, then we don't need to clip
1454 // the content area (PDF area clips to the page size). Otherwise,
1455 // we have to clip to the content area; we've already applied the
1456 // initial transform, so just clip to the device size.
1457 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001458 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1459 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001460 emit_clip(NULL, &r, &data);
1461 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001462
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001463 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001464
reed@google.com5667afc2011-06-27 14:42:15 +00001465 // potentially we could cache this SkData, and only rebuild it if we
1466 // see that our state has changed.
1467 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001468}
1469
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001470#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001471/* Draws an inverse filled path by using Path Ops to compute the positive
1472 * inverse using the current clip as the inverse bounds.
1473 * Return true if this was an inverse path and was properly handled,
1474 * otherwise returns false and the normal drawing routine should continue,
1475 * either as a (incorrect) fallback or because the path was not inverse
1476 * in the first place.
1477 */
1478bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001479 const SkPaint& paint, bool pathIsMutable,
1480 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001481 if (!origPath.isInverseFillType()) {
1482 return false;
1483 }
1484
1485 if (d.fClip->isEmpty()) {
1486 return false;
1487 }
1488
1489 SkPath modifiedPath;
1490 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1491 SkPaint noInversePaint(paint);
1492
1493 // Merge stroking operations into final path.
1494 if (SkPaint::kStroke_Style == paint.getStyle() ||
1495 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1496 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1497 if (doFillPath) {
1498 noInversePaint.setStyle(SkPaint::kFill_Style);
1499 noInversePaint.setStrokeWidth(0);
1500 pathPtr = &modifiedPath;
1501 } else {
1502 // To be consistent with the raster output, hairline strokes
1503 // are rendered as non-inverted.
1504 modifiedPath.toggleInverseFillType();
1505 drawPath(d, modifiedPath, paint, NULL, true);
1506 return true;
1507 }
1508 }
1509
1510 // Get bounds of clip in current transform space
1511 // (clip bounds are given in device space).
1512 SkRect bounds;
1513 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001514 SkMatrix totalMatrix = *d.fMatrix;
1515 if (prePathMatrix) {
1516 totalMatrix.preConcat(*prePathMatrix);
1517 }
1518 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001519 return false;
1520 }
1521 bounds.set(d.fClip->getBounds());
1522 transformInverse.mapRect(&bounds);
1523
1524 // Extend the bounds by the line width (plus some padding)
1525 // so the edge doesn't cause a visible stroke.
1526 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1527 paint.getStrokeWidth() + SK_Scalar1);
1528
1529 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1530 return false;
1531 }
1532
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001533 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001534 return true;
1535}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001536#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001537
epoger@google.comb58772f2013-03-08 09:09:10 +00001538bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1539 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001540 SkAnnotation* annotationInfo = p.getAnnotation();
1541 if (!annotationInfo) {
1542 return false;
1543 }
1544 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001545 if (urlData) {
1546 handleLinkToURL(urlData, r, matrix);
1547 return p.isNoDrawAnnotation();
1548 }
1549 SkData* linkToName = annotationInfo->find(SkAnnotationKeys::Link_Named_Dest_Key());
1550 if (linkToName) {
1551 handleLinkToNamedDest(linkToName, r, matrix);
1552 return p.isNoDrawAnnotation();
1553 }
1554 return false;
1555}
1556
1557bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1558 const SkMatrix& matrix,
1559 const SkPaint& paint) {
1560 SkAnnotation* annotationInfo = paint.getAnnotation();
1561 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001562 return false;
1563 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001564 SkData* nameData = annotationInfo->find(SkAnnotationKeys::Define_Named_Dest_Key());
1565 if (nameData) {
1566 for (size_t i = 0; i < count; i++) {
1567 defineNamedDestination(nameData, points[i], matrix);
1568 }
1569 return paint.isNoDrawAnnotation();
1570 }
1571 return false;
1572}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001573
epoger@google.comb58772f2013-03-08 09:09:10 +00001574SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r, const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001575 SkMatrix transform = matrix;
1576 transform.postConcat(fInitialTransform);
1577 SkRect translatedRect;
1578 transform.mapRect(&translatedRect, r);
1579
reed@google.com2a006c12012-09-19 17:05:55 +00001580 if (NULL == fAnnotations) {
1581 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001582 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001583 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001584 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001585 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001586
epoger@google.comb58772f2013-03-08 09:09:10 +00001587 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001588 border->reserve(3);
1589 border->appendInt(0); // Horizontal corner radius.
1590 border->appendInt(0); // Vertical corner radius.
1591 border->appendInt(0); // Width, 0 = no border.
1592 annotation->insert("Border", border.get());
1593
epoger@google.comb58772f2013-03-08 09:09:10 +00001594 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001595 rect->reserve(4);
1596 rect->appendScalar(translatedRect.fLeft);
1597 rect->appendScalar(translatedRect.fTop);
1598 rect->appendScalar(translatedRect.fRight);
1599 rect->appendScalar(translatedRect.fBottom);
1600 annotation->insert("Rect", rect.get());
1601
epoger@google.comb58772f2013-03-08 09:09:10 +00001602 return annotation;
1603}
epoger@google.com1cad8982013-03-06 00:05:13 +00001604
epoger@google.comb58772f2013-03-08 09:09:10 +00001605void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1606 const SkMatrix& matrix) {
1607 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1608
1609 SkString url(static_cast<const char *>(urlData->data()),
1610 urlData->size() - 1);
1611 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1612 action->insertName("S", "URI");
1613 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1614 annotation->insert("A", action.get());
1615}
1616
1617void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1618 const SkMatrix& matrix) {
1619 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1620 SkString name(static_cast<const char *>(nameData->data()),
1621 nameData->size() - 1);
1622 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1623}
1624
1625struct NamedDestination {
1626 const SkData* nameData;
1627 SkPoint point;
1628
1629 NamedDestination(const SkData* nameData, const SkPoint& point)
1630 : nameData(nameData), point(point) {
1631 nameData->ref();
1632 }
1633
1634 ~NamedDestination() {
1635 nameData->unref();
1636 }
1637};
1638
1639void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1640 const SkMatrix& matrix) {
1641 SkMatrix transform = matrix;
1642 transform.postConcat(fInitialTransform);
1643 SkPoint translatedPoint;
1644 transform.mapXY(point.x(), point.y(), &translatedPoint);
1645 fNamedDestinations.push(
1646 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1647}
1648
1649void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1650 int nDest = fNamedDestinations.count();
1651 for (int i = 0; i < nDest; i++) {
1652 NamedDestination* dest = fNamedDestinations[i];
1653 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1654 pdfDest->reserve(5);
1655 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1656 pdfDest->appendName("XYZ");
1657 pdfDest->appendScalar(dest->point.x());
1658 pdfDest->appendScalar(dest->point.y());
1659 pdfDest->appendInt(0); // Leave zoom unchanged
1660 dict->insert(static_cast<const char *>(dest->nameData->data()), pdfDest);
1661 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001662}
1663
reed@google.comfc641d02012-09-20 17:52:20 +00001664SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1665 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001666 // We always draw the form xobjects that we create back into the device, so
1667 // we simply preserve the font usage instead of pulling it out and merging
1668 // it back in later.
1669 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001670 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001671 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001672}
1673
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001674void SkPDFDevice::clearClipFromContent(const SkClipStack* clipStack,
1675 const SkRegion& clipRegion) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001676 if (clipRegion.isEmpty() || isContentEmpty()) {
1677 return;
1678 }
reed@google.comfc641d02012-09-20 17:52:20 +00001679 SkAutoTUnref<SkPDFFormXObject> curContent(createFormXObjectFromDevice());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001680
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001681 // Redraw what we already had, but with the clip as a mask.
reed@google.comfc641d02012-09-20 17:52:20 +00001682 drawFormXObjectWithClip(curContent, clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001683}
1684
1685void SkPDFDevice::drawFormXObjectWithClip(SkPDFFormXObject* xobject,
1686 const SkClipStack* clipStack,
1687 const SkRegion& clipRegion,
1688 bool invertClip) {
1689 if (clipRegion.isEmpty() && !invertClip) {
1690 return;
1691 }
1692
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001693 // Create the mask.
1694 SkMatrix identity;
1695 identity.reset();
1696 SkDraw draw;
1697 draw.fMatrix = &identity;
1698 draw.fClip = &clipRegion;
1699 draw.fClipStack = clipStack;
1700 SkPaint stockPaint;
1701 this->drawPaint(draw, stockPaint);
reed@google.comfc641d02012-09-20 17:52:20 +00001702 SkAutoTUnref<SkPDFFormXObject> maskFormXObject(createFormXObjectFromDevice());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001703 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001704 SkPDFGraphicState::GetSMaskGraphicState(maskFormXObject, invertClip,
1705 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001706
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001707 // Draw the xobject with the clip as a mask.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001708 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001709 identity, stockPaint);
1710 if (!content.entry()) {
1711 return;
1712 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001713 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001714 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001715 SkPDFUtils::DrawFormXObject(fXObjectResources.count(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001716 &content.entry()->fContent);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001717 fXObjectResources.push(xobject);
1718 xobject->ref();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001719
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001720 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001721 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001722 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001723}
1724
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001725ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1726 const SkRegion& clipRegion,
1727 const SkMatrix& matrix,
1728 const SkPaint& paint,
1729 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001730 SkPDFFormXObject** dst) {
1731 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001732 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001733 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001734 }
1735
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001736 // The clip stack can come from an SkDraw where it is technically optional.
1737 SkClipStack synthesizedClipStack;
1738 if (clipStack == NULL) {
1739 if (clipRegion == fExistingClipRegion) {
1740 clipStack = &fExistingClipStack;
1741 } else {
1742 // GraphicStackState::updateClip expects the clip stack to have
1743 // fExistingClip as a prefix, so start there, then set the clip
1744 // to the passed region.
1745 synthesizedClipStack = fExistingClipStack;
1746 SkPath clipPath;
1747 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001748 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1749 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001750 clipStack = &synthesizedClipStack;
1751 }
1752 }
1753
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001754 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1755 if (paint.getXfermode()) {
1756 paint.getXfermode()->asMode(&xfermode);
1757 }
1758
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001759 if (xfermode == SkXfermode::kClear_Mode ||
1760 xfermode == SkXfermode::kSrc_Mode) {
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001761 this->clearClipFromContent(clipStack, clipRegion);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001762 } else if (xfermode == SkXfermode::kSrcIn_Mode ||
1763 xfermode == SkXfermode::kDstIn_Mode ||
1764 xfermode == SkXfermode::kSrcOut_Mode ||
1765 xfermode == SkXfermode::kDstOut_Mode) {
1766 // For the following modes, we use both source and destination, but
1767 // we use one as a smask for the other, so we have to make form xobjects
1768 // out of both of them: SrcIn, DstIn, SrcOut, DstOut.
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001769 if (isContentEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001770 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001771 } else {
reed@google.comfc641d02012-09-20 17:52:20 +00001772 *dst = createFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001773 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001774 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001775 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001776 // SrcAtop, DestAtop, Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001777
1778 // These xfer modes don't draw source at all.
1779 if (xfermode == SkXfermode::kClear_Mode ||
1780 xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001781 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001782 }
1783
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001784 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001785 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001786
1787 ContentEntry* lastContentEntry = getLastContentEntry();
1788 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1789 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001790 } else {
1791 newEntry.reset(new ContentEntry);
1792 entry = newEntry.get();
1793 }
1794
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001795 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001796 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001797 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1798 entry->fState.compareInitialState(lastContentEntry->fState)) {
1799 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001800 }
1801
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001802 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001803 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001804 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001805 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001806 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001807 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001808 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001809 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001810 lastContentEntry->fNext.reset(entry);
1811 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001812 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001813 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001814 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001815}
1816
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001817void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
1818 SkPDFFormXObject* dst) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001819 if (xfermode != SkXfermode::kSrcIn_Mode &&
1820 xfermode != SkXfermode::kDstIn_Mode &&
1821 xfermode != SkXfermode::kSrcOut_Mode &&
1822 xfermode != SkXfermode::kDstOut_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001823 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001824 return;
1825 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001826
1827 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001828 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001829 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001830 // We have to make a copy of these here because changing the current
1831 // content into a form xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001832 SkClipStack clipStack = contentEntries->fState.fClipStack;
1833 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001834
reed@google.comfc641d02012-09-20 17:52:20 +00001835 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001836 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001837 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001838 }
1839
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001840 drawFormXObjectWithClip(dst, &clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001841
1842 // We've redrawn dst minus the clip area, if there's no src, we're done.
1843 if (!srcFormXObject.get()) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001844 return;
1845 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001846
1847 SkMatrix identity;
1848 identity.reset();
1849 SkPaint stockPaint;
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001850 ScopedContentEntry inClipContentEntry(this, &fExistingClipStack,
1851 fExistingClipRegion, identity,
1852 stockPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001853 if (!inClipContentEntry.entry()) {
1854 return;
1855 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001856
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001857 SkAutoTUnref<SkPDFGraphicState> sMaskGS;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001858 if (xfermode == SkXfermode::kSrcIn_Mode ||
1859 xfermode == SkXfermode::kSrcOut_Mode) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001860 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001861 dst,
1862 xfermode == SkXfermode::kSrcOut_Mode,
1863 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001864 fXObjectResources.push(srcFormXObject.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001865 srcFormXObject.get()->ref();
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001866 } else {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001867 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001868 srcFormXObject.get(),
1869 xfermode == SkXfermode::kDstOut_Mode,
1870 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001871 // dst already added to fXObjectResources in drawFormXObjectWithClip.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001872 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001873 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001874 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001875
1876 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001877 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001878
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001879 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001880 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001881 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001882}
1883
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001884bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001885 ContentEntry* contentEntries = getContentEntries()->get();
1886 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1887 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001888 return true;
1889 }
1890 return false;
1891}
1892
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001893void SkPDFDevice::populateGraphicStateEntryFromPaint(
1894 const SkMatrix& matrix,
1895 const SkClipStack& clipStack,
1896 const SkRegion& clipRegion,
1897 const SkPaint& paint,
1898 bool hasText,
1899 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001900 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001901
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001902 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1903 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001904
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001905 entry->fMatrix = matrix;
1906 entry->fClipStack = clipStack;
1907 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001908 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1909 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001910
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001911 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001912 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001913 const SkShader* shader = paint.getShader();
1914 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001915 if (shader) {
1916 // PDF positions patterns relative to the initial transform, so
1917 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001918 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001919 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001920
1921 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001922 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001923 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001924
1925 // We need to apply the initial transform to bounds in order to get
1926 // bounds in a consistent coordinate system.
1927 SkRect boundsTemp;
1928 boundsTemp.set(bounds);
1929 fInitialTransform.mapRect(&boundsTemp);
1930 boundsTemp.roundOut(&bounds);
1931
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001932 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001933
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001934 if (pdfShader.get()) {
1935 // pdfShader has been canonicalized so we can directly compare
1936 // pointers.
1937 int resourceIndex = fShaderResources.find(pdfShader.get());
1938 if (resourceIndex < 0) {
1939 resourceIndex = fShaderResources.count();
1940 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001941 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001942 }
1943 entry->fShaderIndex = resourceIndex;
1944 } else {
1945 // A color shader is treated as an invalid shader so we don't have
1946 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001947 SkShader::GradientInfo gradientInfo;
1948 SkColor gradientColor;
1949 gradientInfo.fColors = &gradientColor;
1950 gradientInfo.fColorOffsets = NULL;
1951 gradientInfo.fColorCount = 1;
1952 if (shader->asAGradient(&gradientInfo) ==
1953 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001954 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1955 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001956 }
1957 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001958 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001959
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001960 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001961 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001962 newGraphicState.reset(
1963 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001964 } else {
1965 SkPaint newPaint = paint;
1966 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001967 newGraphicState.reset(
1968 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001969 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001970 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001971 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001972
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001973 if (hasText) {
1974 entry->fTextScaleX = paint.getTextScaleX();
1975 entry->fTextFill = paint.getStyle();
1976 } else {
1977 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001978 }
1979}
1980
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001981int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
1982 // Assumes that gs has been canonicalized (so we can directly compare
1983 // pointers).
1984 int result = fGraphicStateResources.find(gs);
1985 if (result < 0) {
1986 result = fGraphicStateResources.count();
1987 fGraphicStateResources.push(gs);
1988 gs->ref();
1989 }
1990 return result;
1991}
1992
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001993void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
1994 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001995 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001996 if (contentEntry->fState.fFont == NULL ||
1997 contentEntry->fState.fTextSize != paint.getTextSize() ||
1998 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001999 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002000 contentEntry->fContent.writeText("/");
2001 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2002 SkPDFResourceDict::kFont_ResourceType,
2003 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002004 contentEntry->fContent.writeText(" ");
2005 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2006 contentEntry->fContent.writeText(" Tf\n");
2007 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002008 }
2009}
2010
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002011int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002012 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002013 int resourceIndex = fFontResources.find(newFont.get());
2014 if (resourceIndex < 0) {
2015 resourceIndex = fFontResources.count();
2016 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002017 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002018 }
2019 return resourceIndex;
2020}
2021
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002022void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002023 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002024 const SkRegion& origClipRegion,
2025 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002026 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002027 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002028 SkMatrix matrix = origMatrix;
2029 SkRegion perspectiveBounds;
2030 const SkRegion* clipRegion = &origClipRegion;
2031 SkBitmap perspectiveBitmap;
2032 const SkBitmap* bitmap = &origBitmap;
2033 SkBitmap tmpSubsetBitmap;
2034
2035 // Rasterize the bitmap using perspective in a new bitmap.
2036 if (origMatrix.hasPerspective()) {
2037 SkBitmap* subsetBitmap;
2038 if (srcRect) {
2039 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2040 return;
2041 }
2042 subsetBitmap = &tmpSubsetBitmap;
2043 } else {
2044 subsetBitmap = &tmpSubsetBitmap;
2045 *subsetBitmap = origBitmap;
2046 }
2047 srcRect = NULL;
2048
2049 // Transform the bitmap in the new space.
2050 SkPath perspectiveOutline;
2051 perspectiveOutline.addRect(
2052 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2053 SkIntToScalar(subsetBitmap->height())));
2054 perspectiveOutline.transform(origMatrix);
2055
2056 // TODO(edisonn): perf - use current clip too.
2057 // Retrieve the bounds of the new shape.
2058 SkRect bounds = perspectiveOutline.getBounds();
2059
2060 // TODO(edisonn): add DPI settings. Currently 1 pixel/point, which does
2061 // not look great, but it is not producing large PDFs.
2062
2063 // TODO(edisonn): A better approach would be to use a bitmap shader
2064 // (in clamp mode) and draw a rect over the entire bounding box. Then
2065 // intersect perspectiveOutline to the clip. That will avoid introducing
2066 // alpha to the image while still giving good behavior at the edge of
2067 // the image. Avoiding alpha will reduce the pdf size and generation
2068 // CPU time some.
2069
2070 perspectiveBitmap.setConfig(SkBitmap::kARGB_8888_Config,
2071 SkScalarCeilToInt(bounds.width()),
2072 SkScalarCeilToInt(bounds.height()));
2073 perspectiveBitmap.allocPixels();
2074 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2075
2076 SkBitmapDevice device(perspectiveBitmap);
2077 SkCanvas canvas(&device);
2078
2079 SkScalar deltaX = bounds.left();
2080 SkScalar deltaY = bounds.top();
2081
2082 SkMatrix offsetMatrix = origMatrix;
2083 offsetMatrix.postTranslate(-deltaX, -deltaY);
2084
2085 // Translate the draw in the new canvas, so we perfectly fit the
2086 // shape in the bitmap.
2087 canvas.setMatrix(offsetMatrix);
2088
2089 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2090
2091 // Make sure the final bits are in the bitmap.
2092 canvas.flush();
2093
2094 // In the new space, we use the identity matrix translated.
2095 matrix.setTranslate(deltaX, deltaY);
2096 perspectiveBounds.setRect(
2097 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2098 SkScalarFloorToInt(bounds.y()),
2099 SkScalarCeilToInt(bounds.width()),
2100 SkScalarCeilToInt(bounds.height())));
2101 clipRegion = &perspectiveBounds;
2102 srcRect = NULL;
2103 bitmap = &perspectiveBitmap;
2104 }
2105
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002106 SkMatrix scaled;
2107 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002108 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2109 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002110 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002111 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002112 scaled.postScale(SkIntToScalar(subset.width()),
2113 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002114 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002115 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002116 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002117 return;
2118 }
2119
2120 if (srcRect && !subset.intersect(*srcRect)) {
2121 return;
2122 }
2123
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002124 SkPDFImage* image = SkPDFImage::CreateImage(*bitmap, subset, fEncoder);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002125 if (!image) {
2126 return;
2127 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002128
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002129 fXObjectResources.push(image); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002130 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002131 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002132}
reed@google.com982cb872011-12-07 18:34:08 +00002133
2134bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2135 SkCanvas::Config8888) {
2136 return false;
2137}
reed@google.comb55deeb2012-01-06 14:43:09 +00002138
2139bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2140 return false;
2141}