blob: e90edb1408fa790592e2f0766305eb923e72d3b6 [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.orgdc37e202013-10-18 20:16:34 +0000651 if (matrix.hasPerspective() ||
652 (paint.getShader() &&
653 paint.getShader()->getLocalMatrix().hasPerspective())) {
654 // Just report that PDF does not supports perspective
655 // TODO(edisonn): update the shape when possible
656 // or dump in an image otherwise
657 NOT_IMPLEMENTED(true, false);
658 return;
659 }
660
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000661 if (paint.getXfermode()) {
662 paint.getXfermode()->asMode(&fXfermode);
663 }
664 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
665 matrix, paint, hasText,
666 &fDstFormXObject);
667 }
668};
669
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000670////////////////////////////////////////////////////////////////////////////////
671
ctguil@chromium.org15261292011-04-29 17:54:16 +0000672static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000673 const SkMatrix* initialTransform) {
reed@android.comf2b98d62010-12-20 18:26:13 +0000674 SkBitmap bitmap;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000675 if (initialTransform) {
676 // Compute the size of the drawing area.
677 SkVector drawingSize;
678 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000679 drawingSize.set(SkIntToScalar(contentSize.fWidth),
680 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000681 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000682 // This shouldn't happen, initial transform should be invertible.
683 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000684 inverse.reset();
685 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000686 inverse.mapVectors(&drawingSize, 1);
687 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
688 bitmap.setConfig(SkBitmap::kNo_Config, abs(size.fWidth),
689 abs(size.fHeight));
690 } else {
691 bitmap.setConfig(SkBitmap::kNo_Config, abs(contentSize.fWidth),
692 abs(contentSize.fHeight));
693 }
694
reed@android.comf2b98d62010-12-20 18:26:13 +0000695 return bitmap;
696}
697
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000698// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000699SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000700 const SkMatrix& initialTransform)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000701 : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
ctguil@chromium.org15261292011-04-29 17:54:16 +0000702 fPageSize(pageSize),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000703 fContentSize(contentSize),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000704 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000705 fLastMarginContentEntry(NULL),
edisonn@google.comd9dfa182013-04-24 13:01:01 +0000706 fClipStack(NULL),
707 fEncoder(NULL) {
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000708 // just report that PDF does not supports perspective
709 // TODO(edisonn): update the shape when possible
710 // or dump in an image otherwise
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000711 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
712
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000713 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000714 // origin at the bottom left. This matrix corrects for that. But that only
715 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000716 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
717 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000718 fInitialTransform.preConcat(initialTransform);
719
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000720 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000721 fExistingClipRegion.setRect(existingClip);
722
723 this->init();
724}
725
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000726// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000727SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
728 const SkClipStack& existingClipStack,
729 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000730 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000731 fPageSize(layerSize),
732 fContentSize(layerSize),
733 fExistingClipStack(existingClipStack),
734 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000735 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000736 fLastMarginContentEntry(NULL),
737 fClipStack(NULL) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000738 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000739 this->init();
740}
741
742SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000743 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000744}
745
746void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000747 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000748 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000749 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000750 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000751 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000752 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000753 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000754 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000755 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
756 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000757}
758
vandebo@chromium.org98594282011-07-25 22:34:12 +0000759void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000760 fGraphicStateResources.unrefAll();
761 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000762 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000763 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000764 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000765 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000766 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000767
vandebo@chromium.org98594282011-07-25 22:34:12 +0000768 if (clearFontUsage) {
769 fFontGlyphUsage->reset();
770 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000771}
772
reed@google.com982cb872011-12-07 18:34:08 +0000773uint32_t SkPDFDevice::getDeviceCapabilities() {
774 return kVector_Capability;
775}
776
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000777void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000778 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000779 this->init();
780
781 SkPaint paint;
782 paint.setColor(color);
783 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000784 SkMatrix identity;
785 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000786 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
787 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000788 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000789}
790
791void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000792 SkPaint newPaint = paint;
793 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000794 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000795 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000796}
797
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000798void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
799 ContentEntry* contentEntry) {
800 if (!contentEntry) {
801 return;
802 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000803 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
804 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000805 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000806 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000807 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000808 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000809 inverse.mapRect(&bbox);
810
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000811 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000812 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000813 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000814}
815
816void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
817 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000818 const SkPaint& passedPaint) {
819 if (count == 0) {
820 return;
821 }
822
epoger@google.comb58772f2013-03-08 09:09:10 +0000823 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
824 return;
825 }
826
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000827 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
828 // We only use this when there's a path effect because of the overhead
829 // of multiple calls to setUpContentEntry it causes.
830 if (passedPaint.getPathEffect()) {
831 if (d.fClip->isEmpty()) {
832 return;
833 }
834 SkDraw pointDraw(d);
835 pointDraw.fDevice = this;
836 pointDraw.drawPoints(mode, count, points, passedPaint, true);
837 return;
838 }
839
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000840 const SkPaint* paint = &passedPaint;
841 SkPaint modifiedPaint;
842
843 if (mode == SkCanvas::kPoints_PointMode &&
844 paint->getStrokeCap() != SkPaint::kRound_Cap) {
845 modifiedPaint = *paint;
846 paint = &modifiedPaint;
847 if (paint->getStrokeWidth()) {
848 // PDF won't draw a single point with square/butt caps because the
849 // orientation is ambiguous. Draw a rectangle instead.
850 modifiedPaint.setStyle(SkPaint::kFill_Style);
851 SkScalar strokeWidth = paint->getStrokeWidth();
852 SkScalar halfStroke = SkScalarHalf(strokeWidth);
853 for (size_t i = 0; i < count; i++) {
854 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
855 r.inset(-halfStroke, -halfStroke);
856 drawRect(d, r, modifiedPaint);
857 }
858 return;
859 } else {
860 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
861 }
862 }
863
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000864 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000865 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000866 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000867 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000868
869 switch (mode) {
870 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000871 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000872 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000873 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000874 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000875 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000876 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000877 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000878 break;
879 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000880 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000881 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000882 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000883 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000884 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000885 &content.entry()->fContent);
886 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000887 }
888 break;
889 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000890 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
891 for (size_t i = 0; i < count; i++) {
892 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000893 &content.entry()->fContent);
894 SkPDFUtils::ClosePath(&content.entry()->fContent);
895 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000896 }
897 break;
898 default:
899 SkASSERT(false);
900 }
901}
902
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000903void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000904 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000905 SkRect r = rect;
906 r.sort();
907
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000908 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000909 if (d.fClip->isEmpty()) {
910 return;
911 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000912 SkPath path;
913 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000914 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000915 return;
916 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000917
epoger@google.comb58772f2013-03-08 09:09:10 +0000918 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000919 return;
920 }
921
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000922 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000923 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000924 return;
925 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000926 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000927 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000928 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000929}
930
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000931void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000932 const SkPaint& paint, const SkMatrix* prePathMatrix,
933 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000934 SkPath modifiedPath;
935 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
936
937 SkMatrix matrix = *d.fMatrix;
938 if (prePathMatrix) {
939 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
940 if (!pathIsMutable) {
941 pathPtr = &modifiedPath;
942 pathIsMutable = true;
943 }
944 origPath.transform(*prePathMatrix, pathPtr);
945 } else {
946 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000947 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000948 return;
949 }
950 }
951 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000952
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000953 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000954 if (d.fClip->isEmpty()) {
955 return;
956 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000957 if (!pathIsMutable) {
958 pathPtr = &modifiedPath;
959 pathIsMutable = true;
960 }
961 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000962
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000963 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000964 noEffectPaint.setPathEffect(NULL);
965 if (fill) {
966 noEffectPaint.setStyle(SkPaint::kFill_Style);
967 } else {
968 noEffectPaint.setStyle(SkPaint::kStroke_Style);
969 noEffectPaint.setStrokeWidth(0);
970 }
971 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000972 return;
973 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000974
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000975#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000976 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000977 return;
978 }
979#endif
980
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000981 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000982 return;
983 }
984
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000985 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000986 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000987 return;
988 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000989 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
990 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000991 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000992 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000993}
994
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000995void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
996 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000997 const SkPaint& paint,
998 SkCanvas::DrawBitmapRectFlags flags) {
999 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001000 SkMatrix matrix;
1001 SkRect bitmapBounds, tmpSrc, tmpDst;
1002 SkBitmap tmpBitmap;
1003
1004 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1005
1006 // Compute matrix from the two rectangles
1007 if (src) {
1008 tmpSrc = *src;
1009 } else {
1010 tmpSrc = bitmapBounds;
1011 }
1012 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1013
1014 const SkBitmap* bitmapPtr = &bitmap;
1015
1016 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1017 // needed (if the src was clipped). No check needed if src==null.
1018 if (src) {
1019 if (!bitmapBounds.contains(*src)) {
1020 if (!tmpSrc.intersect(bitmapBounds)) {
1021 return; // nothing to draw
1022 }
1023 // recompute dst, based on the smaller tmpSrc
1024 matrix.mapRect(&tmpDst, tmpSrc);
1025 }
1026
1027 // since we may need to clamp to the borders of the src rect within
1028 // the bitmap, we extract a subset.
1029 // TODO: make sure this is handled in drawBitmap and remove from here.
1030 SkIRect srcIR;
1031 tmpSrc.roundOut(&srcIR);
1032 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1033 return;
1034 }
1035 bitmapPtr = &tmpBitmap;
1036
1037 // Since we did an extract, we need to adjust the matrix accordingly
1038 SkScalar dx = 0, dy = 0;
1039 if (srcIR.fLeft > 0) {
1040 dx = SkIntToScalar(srcIR.fLeft);
1041 }
1042 if (srcIR.fTop > 0) {
1043 dy = SkIntToScalar(srcIR.fTop);
1044 }
1045 if (dx || dy) {
1046 matrix.preTranslate(dx, dy);
1047 }
1048 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001049 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001050}
1051
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001052void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001053 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001054 if (d.fClip->isEmpty()) {
1055 return;
1056 }
1057
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001058 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001059 transform.postConcat(*d.fMatrix);
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001060 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001061}
1062
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001063void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001064 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001065 if (d.fClip->isEmpty()) {
1066 return;
1067 }
1068
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001069 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001070 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001071 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001072}
1073
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001074void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001075 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001076 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1077 if (paint.getMaskFilter() != NULL) {
1078 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1079 // making text unreadable (e.g. same text twice when using CSS shadows).
1080 return;
1081 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001082 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001083 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001084 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001085 return;
1086 }
1087
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001088 SkGlyphStorage storage(0);
1089 uint16_t* glyphIDs = NULL;
1090 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1091 &glyphIDs);
1092 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001093
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001094 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001095 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001096 content.entry()->fContent.writeText("BT\n");
1097 set_text_transform(x, y, textPaint.getTextSkewX(),
1098 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001099 size_t consumedGlyphCount = 0;
1100 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001101 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1102 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001103 size_t availableGlyphs =
1104 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1105 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001106 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1107 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001108 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001109 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001110 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001111 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001112 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001113 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001114 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001115 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001116}
1117
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001118void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001119 const SkScalar pos[], SkScalar constY,
1120 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001121 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1122 if (paint.getMaskFilter() != NULL) {
1123 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1124 // making text unreadable (e.g. same text twice when using CSS shadows).
1125 return;
1126 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001127 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001128 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001129 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001130 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001131 return;
1132 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001133
djsollen@google.com5df5e612013-10-03 14:42:24 +00001134#ifdef SK_BUILD_FOR_ANDROID
1135 /*
1136 * In the case that we have enabled fallback fonts on Android we need to
1137 * take the following steps to ensure that the PDF draws all characters,
1138 * regardless of their underlying font file, correctly.
1139 *
1140 * 1. Convert input into GlyphID encoding if it currently is not
1141 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1142 * glyph resolves to
1143 * 3. Iterate over those typefaces and recursively call this function with
1144 * only the glyphs (and their positions) that the typeface is capable of
1145 * resolving.
1146 */
1147 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1148 uint16_t* glyphIDs = NULL;
1149 SkGlyphStorage tmpStorage(0);
1150 size_t numGlyphs = 0;
1151
1152 // convert to glyphIDs
1153 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1154 numGlyphs = len / 2;
1155 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1156 } else {
1157 numGlyphs = paint.textToGlyphs(text, len, NULL);
1158 tmpStorage.reset(numGlyphs);
1159 paint.textToGlyphs(text, len, tmpStorage.get());
1160 glyphIDs = tmpStorage.get();
1161 }
1162
1163 // if no typeface is provided in the paint get the default
1164 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1165 if (NULL == origFace.get()) {
1166 origFace.reset(SkTypeface::RefDefault());
1167 }
1168 const uint16_t origGlyphCount = origFace->countGlyphs();
1169
1170 // keep a list of the already visited typefaces and some data about them
1171 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1172
1173 // find all the typefaces needed to resolve this run of text
1174 bool usesOriginalTypeface = false;
1175 for (uint16_t x = 0; x < numGlyphs; ++x) {
1176 // optimization that checks to see if original typeface can resolve the glyph
1177 if (glyphIDs[x] < origGlyphCount) {
1178 usesOriginalTypeface = true;
1179 continue;
1180 }
1181
1182 // find the fallback typeface that supports this glyph
1183 TypefaceFallbackData data;
1184 data.typeface = SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1185 paint.getPaintOptionsAndroid(),
1186 &data.lowerBounds, &data.upperBounds);
1187 // add the typeface and its data if we don't have it
1188 if (data.typeface && !visitedTypefaces.contains(data)) {
1189 visitedTypefaces.push(data);
1190 }
1191 }
1192
1193 // if the original font was used then add it to the list as well
1194 if (usesOriginalTypeface) {
1195 TypefaceFallbackData* data = visitedTypefaces.push();
1196 data->typeface = origFace.get();
1197 data->lowerBounds = 0;
1198 data->upperBounds = origGlyphCount;
1199 }
1200
1201 // keep a scratch glyph and pos storage
1202 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1203 SkScalar* tmpPos = posStorage.get();
1204 SkGlyphStorage glyphStorage(numGlyphs);
1205 uint16_t* tmpGlyphIDs = glyphStorage.get();
1206
1207 // loop through all the valid typefaces, trim the glyphs to only those
1208 // resolved by the typeface, and then draw that run of glyphs
1209 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1210 const TypefaceFallbackData& data = visitedTypefaces[x];
1211
1212 int tmpGlyphCount = 0;
1213 for (uint16_t y = 0; y < numGlyphs; ++y) {
1214 if (glyphIDs[y] >= data.lowerBounds && glyphIDs[y] < data.upperBounds) {
1215 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1216 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1217 &(pos[y * scalarsPerPos]),
1218 scalarsPerPos * sizeof(SkScalar));
1219 tmpGlyphCount++;
1220 }
1221 }
1222
1223 // recursively call this function with the right typeface
1224 SkPaint tmpPaint = paint;
1225 tmpPaint.setTypeface(data.typeface);
1226 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1227
1228 // turn off fallback chaining
1229 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1230 paintOpts.setUseFontFallbacks(false);
1231 tmpPaint.setPaintOptionsAndroid(paintOpts);
1232
1233 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1234 scalarsPerPos, tmpPaint);
1235 }
1236 return;
1237 }
1238#endif
1239
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001240 SkGlyphStorage storage(0);
1241 uint16_t* glyphIDs = NULL;
1242 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1243 &glyphIDs);
1244 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001245
1246 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001247 content.entry()->fContent.writeText("BT\n");
1248 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001249 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001250 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001251 uint16_t encodedValue = glyphIDs[i];
1252 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001253 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001254 i--;
1255 continue;
1256 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001257 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001258 SkScalar x = pos[i * scalarsPerPos];
1259 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001260 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001261 set_text_transform(x, y, textPaint.getTextSkewX(),
1262 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001263 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001264 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001265 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001266 content.entry()->fContent.writeText(encodedString.c_str());
1267 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001268 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001269 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001270}
1271
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001272void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001273 const SkPath& path, const SkMatrix* matrix,
1274 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001275 if (d.fClip->isEmpty()) {
1276 return;
1277 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001278 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001279}
1280
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001281void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001282 int vertexCount, const SkPoint verts[],
1283 const SkPoint texs[], const SkColor colors[],
1284 SkXfermode* xmode, const uint16_t indices[],
1285 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001286 if (d.fClip->isEmpty()) {
1287 return;
1288 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001289 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001290}
1291
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001292void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device, int x, int y,
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001293 const SkPaint& paint) {
1294 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1295 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001296 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001297 return;
1298 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001299
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001300 // Assume that a vector capable device means that it's a PDF Device.
1301 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001302 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001303 return;
1304 }
1305
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001306 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001307 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001308 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001309 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001310 return;
1311 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001312
1313 SkPDFFormXObject* xobject = new SkPDFFormXObject(pdfDevice);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001314 fXObjectResources.push(xobject); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001315 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001316 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001317
1318 // Merge glyph sets from the drawn device.
1319 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001320}
1321
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001322void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1323 INHERITED::onAttachToCanvas(canvas);
1324
1325 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1326 fClipStack = canvas->getClipStack();
1327}
1328
1329void SkPDFDevice::onDetachFromCanvas() {
1330 INHERITED::onDetachFromCanvas();
1331
1332 fClipStack = NULL;
1333}
1334
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001335ContentEntry* SkPDFDevice::getLastContentEntry() {
1336 if (fDrawingArea == kContent_DrawingArea) {
1337 return fLastContentEntry;
1338 } else {
1339 return fLastMarginContentEntry;
1340 }
1341}
1342
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001343SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001344 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001345 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001346 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001347 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001348 }
1349}
1350
1351void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1352 if (fDrawingArea == kContent_DrawingArea) {
1353 fLastContentEntry = contentEntry;
1354 } else {
1355 fLastMarginContentEntry = contentEntry;
1356 }
1357}
1358
1359void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001360 // A ScopedContentEntry only exists during the course of a draw call, so
1361 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001362 fDrawingArea = drawingArea;
1363}
1364
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001365SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001366 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001367 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001368
1369 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001370 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001371 fResourceDict->insertResourceAsReference(
1372 SkPDFResourceDict::kExtGState_ResourceType,
1373 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001374 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001375 }
1376
1377 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001378 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001379 fResourceDict->insertResourceAsReference(
1380 SkPDFResourceDict::kXObject_ResourceType,
1381 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001382 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001383 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001384
1385 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001386 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001387 fResourceDict->insertResourceAsReference(
1388 SkPDFResourceDict::kFont_ResourceType,
1389 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001390 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001391 }
1392
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001393 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001394 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001395 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001396 fResourceDict->insertResourceAsReference(
1397 SkPDFResourceDict::kPattern_ResourceType,
1398 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001399 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001400 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001401 }
1402 return fResourceDict;
1403}
1404
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001405const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1406 return fFontResources;
1407}
1408
reed@google.com2a006c12012-09-19 17:05:55 +00001409SkPDFArray* SkPDFDevice::copyMediaBox() const {
1410 // should this be a singleton?
1411 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001412
reed@google.com2a006c12012-09-19 17:05:55 +00001413 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001414 mediaBox->reserve(4);
1415 mediaBox->append(zero.get());
1416 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001417 mediaBox->appendInt(fPageSize.fWidth);
1418 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001419 return mediaBox;
1420}
1421
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001422SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001423 SkMemoryStream* result = new SkMemoryStream;
1424 result->setData(this->copyContentToData())->unref();
1425 return result;
1426}
1427
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001428void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1429 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001430 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1431 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001432 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001433 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001434 SkPoint translation;
1435 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001436 translation.negate();
1437 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1438 translation);
1439 gsState.updateMatrix(entry->fState.fMatrix);
1440 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001441
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001442 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001443 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001444 entry = entry->fNext.get();
1445 }
1446 gsState.drainStack();
1447}
1448
reed@google.com5667afc2011-06-27 14:42:15 +00001449SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001450 SkDynamicMemoryWStream data;
1451 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1452 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001453 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001454
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001455 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1456 // colors the contentArea white before it starts drawing into it and
1457 // that currently acts as our clip.
1458 // Also, think about adding a transform here (or assume that the values
1459 // sent across account for that)
1460 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001461
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001462 // If the content area is the entire page, then we don't need to clip
1463 // the content area (PDF area clips to the page size). Otherwise,
1464 // we have to clip to the content area; we've already applied the
1465 // initial transform, so just clip to the device size.
1466 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001467 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1468 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001469 emit_clip(NULL, &r, &data);
1470 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001471
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001472 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001473
reed@google.com5667afc2011-06-27 14:42:15 +00001474 // potentially we could cache this SkData, and only rebuild it if we
1475 // see that our state has changed.
1476 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001477}
1478
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001479#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001480/* Draws an inverse filled path by using Path Ops to compute the positive
1481 * inverse using the current clip as the inverse bounds.
1482 * Return true if this was an inverse path and was properly handled,
1483 * otherwise returns false and the normal drawing routine should continue,
1484 * either as a (incorrect) fallback or because the path was not inverse
1485 * in the first place.
1486 */
1487bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001488 const SkPaint& paint, bool pathIsMutable,
1489 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001490 if (!origPath.isInverseFillType()) {
1491 return false;
1492 }
1493
1494 if (d.fClip->isEmpty()) {
1495 return false;
1496 }
1497
1498 SkPath modifiedPath;
1499 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1500 SkPaint noInversePaint(paint);
1501
1502 // Merge stroking operations into final path.
1503 if (SkPaint::kStroke_Style == paint.getStyle() ||
1504 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1505 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1506 if (doFillPath) {
1507 noInversePaint.setStyle(SkPaint::kFill_Style);
1508 noInversePaint.setStrokeWidth(0);
1509 pathPtr = &modifiedPath;
1510 } else {
1511 // To be consistent with the raster output, hairline strokes
1512 // are rendered as non-inverted.
1513 modifiedPath.toggleInverseFillType();
1514 drawPath(d, modifiedPath, paint, NULL, true);
1515 return true;
1516 }
1517 }
1518
1519 // Get bounds of clip in current transform space
1520 // (clip bounds are given in device space).
1521 SkRect bounds;
1522 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001523 SkMatrix totalMatrix = *d.fMatrix;
1524 if (prePathMatrix) {
1525 totalMatrix.preConcat(*prePathMatrix);
1526 }
1527 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001528 return false;
1529 }
1530 bounds.set(d.fClip->getBounds());
1531 transformInverse.mapRect(&bounds);
1532
1533 // Extend the bounds by the line width (plus some padding)
1534 // so the edge doesn't cause a visible stroke.
1535 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1536 paint.getStrokeWidth() + SK_Scalar1);
1537
1538 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1539 return false;
1540 }
1541
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001542 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001543 return true;
1544}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001545#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001546
epoger@google.comb58772f2013-03-08 09:09:10 +00001547bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1548 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001549 SkAnnotation* annotationInfo = p.getAnnotation();
1550 if (!annotationInfo) {
1551 return false;
1552 }
1553 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001554 if (urlData) {
1555 handleLinkToURL(urlData, r, matrix);
1556 return p.isNoDrawAnnotation();
1557 }
1558 SkData* linkToName = annotationInfo->find(SkAnnotationKeys::Link_Named_Dest_Key());
1559 if (linkToName) {
1560 handleLinkToNamedDest(linkToName, r, matrix);
1561 return p.isNoDrawAnnotation();
1562 }
1563 return false;
1564}
1565
1566bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1567 const SkMatrix& matrix,
1568 const SkPaint& paint) {
1569 SkAnnotation* annotationInfo = paint.getAnnotation();
1570 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001571 return false;
1572 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001573 SkData* nameData = annotationInfo->find(SkAnnotationKeys::Define_Named_Dest_Key());
1574 if (nameData) {
1575 for (size_t i = 0; i < count; i++) {
1576 defineNamedDestination(nameData, points[i], matrix);
1577 }
1578 return paint.isNoDrawAnnotation();
1579 }
1580 return false;
1581}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001582
epoger@google.comb58772f2013-03-08 09:09:10 +00001583SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r, const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001584 SkMatrix transform = matrix;
1585 transform.postConcat(fInitialTransform);
1586 SkRect translatedRect;
1587 transform.mapRect(&translatedRect, r);
1588
reed@google.com2a006c12012-09-19 17:05:55 +00001589 if (NULL == fAnnotations) {
1590 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001591 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001592 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001593 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001594 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001595
epoger@google.comb58772f2013-03-08 09:09:10 +00001596 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001597 border->reserve(3);
1598 border->appendInt(0); // Horizontal corner radius.
1599 border->appendInt(0); // Vertical corner radius.
1600 border->appendInt(0); // Width, 0 = no border.
1601 annotation->insert("Border", border.get());
1602
epoger@google.comb58772f2013-03-08 09:09:10 +00001603 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001604 rect->reserve(4);
1605 rect->appendScalar(translatedRect.fLeft);
1606 rect->appendScalar(translatedRect.fTop);
1607 rect->appendScalar(translatedRect.fRight);
1608 rect->appendScalar(translatedRect.fBottom);
1609 annotation->insert("Rect", rect.get());
1610
epoger@google.comb58772f2013-03-08 09:09:10 +00001611 return annotation;
1612}
epoger@google.com1cad8982013-03-06 00:05:13 +00001613
epoger@google.comb58772f2013-03-08 09:09:10 +00001614void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1615 const SkMatrix& matrix) {
1616 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1617
1618 SkString url(static_cast<const char *>(urlData->data()),
1619 urlData->size() - 1);
1620 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1621 action->insertName("S", "URI");
1622 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1623 annotation->insert("A", action.get());
1624}
1625
1626void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1627 const SkMatrix& matrix) {
1628 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1629 SkString name(static_cast<const char *>(nameData->data()),
1630 nameData->size() - 1);
1631 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1632}
1633
1634struct NamedDestination {
1635 const SkData* nameData;
1636 SkPoint point;
1637
1638 NamedDestination(const SkData* nameData, const SkPoint& point)
1639 : nameData(nameData), point(point) {
1640 nameData->ref();
1641 }
1642
1643 ~NamedDestination() {
1644 nameData->unref();
1645 }
1646};
1647
1648void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1649 const SkMatrix& matrix) {
1650 SkMatrix transform = matrix;
1651 transform.postConcat(fInitialTransform);
1652 SkPoint translatedPoint;
1653 transform.mapXY(point.x(), point.y(), &translatedPoint);
1654 fNamedDestinations.push(
1655 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1656}
1657
1658void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1659 int nDest = fNamedDestinations.count();
1660 for (int i = 0; i < nDest; i++) {
1661 NamedDestination* dest = fNamedDestinations[i];
1662 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1663 pdfDest->reserve(5);
1664 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1665 pdfDest->appendName("XYZ");
1666 pdfDest->appendScalar(dest->point.x());
1667 pdfDest->appendScalar(dest->point.y());
1668 pdfDest->appendInt(0); // Leave zoom unchanged
1669 dict->insert(static_cast<const char *>(dest->nameData->data()), pdfDest);
1670 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001671}
1672
reed@google.comfc641d02012-09-20 17:52:20 +00001673SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1674 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001675 // We always draw the form xobjects that we create back into the device, so
1676 // we simply preserve the font usage instead of pulling it out and merging
1677 // it back in later.
1678 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001679 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001680 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001681}
1682
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001683void SkPDFDevice::clearClipFromContent(const SkClipStack* clipStack,
1684 const SkRegion& clipRegion) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001685 if (clipRegion.isEmpty() || isContentEmpty()) {
1686 return;
1687 }
reed@google.comfc641d02012-09-20 17:52:20 +00001688 SkAutoTUnref<SkPDFFormXObject> curContent(createFormXObjectFromDevice());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001689
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001690 // Redraw what we already had, but with the clip as a mask.
reed@google.comfc641d02012-09-20 17:52:20 +00001691 drawFormXObjectWithClip(curContent, clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001692}
1693
1694void SkPDFDevice::drawFormXObjectWithClip(SkPDFFormXObject* xobject,
1695 const SkClipStack* clipStack,
1696 const SkRegion& clipRegion,
1697 bool invertClip) {
1698 if (clipRegion.isEmpty() && !invertClip) {
1699 return;
1700 }
1701
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001702 // Create the mask.
1703 SkMatrix identity;
1704 identity.reset();
1705 SkDraw draw;
1706 draw.fMatrix = &identity;
1707 draw.fClip = &clipRegion;
1708 draw.fClipStack = clipStack;
1709 SkPaint stockPaint;
1710 this->drawPaint(draw, stockPaint);
reed@google.comfc641d02012-09-20 17:52:20 +00001711 SkAutoTUnref<SkPDFFormXObject> maskFormXObject(createFormXObjectFromDevice());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001712 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001713 SkPDFGraphicState::GetSMaskGraphicState(maskFormXObject, invertClip,
1714 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001715
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001716 // Draw the xobject with the clip as a mask.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001717 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001718 identity, stockPaint);
1719 if (!content.entry()) {
1720 return;
1721 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001722 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001723 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001724 SkPDFUtils::DrawFormXObject(fXObjectResources.count(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001725 &content.entry()->fContent);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001726 fXObjectResources.push(xobject);
1727 xobject->ref();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001728
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001729 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001730 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001731 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001732}
1733
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001734ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1735 const SkRegion& clipRegion,
1736 const SkMatrix& matrix,
1737 const SkPaint& paint,
1738 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001739 SkPDFFormXObject** dst) {
1740 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001741 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001742 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001743 }
1744
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001745 // The clip stack can come from an SkDraw where it is technically optional.
1746 SkClipStack synthesizedClipStack;
1747 if (clipStack == NULL) {
1748 if (clipRegion == fExistingClipRegion) {
1749 clipStack = &fExistingClipStack;
1750 } else {
1751 // GraphicStackState::updateClip expects the clip stack to have
1752 // fExistingClip as a prefix, so start there, then set the clip
1753 // to the passed region.
1754 synthesizedClipStack = fExistingClipStack;
1755 SkPath clipPath;
1756 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001757 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1758 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001759 clipStack = &synthesizedClipStack;
1760 }
1761 }
1762
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001763 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1764 if (paint.getXfermode()) {
1765 paint.getXfermode()->asMode(&xfermode);
1766 }
1767
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001768 if (xfermode == SkXfermode::kClear_Mode ||
1769 xfermode == SkXfermode::kSrc_Mode) {
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001770 this->clearClipFromContent(clipStack, clipRegion);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001771 } else if (xfermode == SkXfermode::kSrcIn_Mode ||
1772 xfermode == SkXfermode::kDstIn_Mode ||
1773 xfermode == SkXfermode::kSrcOut_Mode ||
1774 xfermode == SkXfermode::kDstOut_Mode) {
1775 // For the following modes, we use both source and destination, but
1776 // we use one as a smask for the other, so we have to make form xobjects
1777 // out of both of them: SrcIn, DstIn, SrcOut, DstOut.
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001778 if (isContentEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001779 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001780 } else {
reed@google.comfc641d02012-09-20 17:52:20 +00001781 *dst = createFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001782 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001783 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001784 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001785 // SrcAtop, DestAtop, Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001786
1787 // These xfer modes don't draw source at all.
1788 if (xfermode == SkXfermode::kClear_Mode ||
1789 xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001790 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001791 }
1792
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001793 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001794 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001795
1796 ContentEntry* lastContentEntry = getLastContentEntry();
1797 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1798 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001799 } else {
1800 newEntry.reset(new ContentEntry);
1801 entry = newEntry.get();
1802 }
1803
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001804 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001805 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001806 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1807 entry->fState.compareInitialState(lastContentEntry->fState)) {
1808 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001809 }
1810
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001811 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001812 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001813 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001814 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001815 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001816 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001817 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001818 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001819 lastContentEntry->fNext.reset(entry);
1820 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001821 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001822 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001823 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001824}
1825
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001826void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
1827 SkPDFFormXObject* dst) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001828 if (xfermode != SkXfermode::kSrcIn_Mode &&
1829 xfermode != SkXfermode::kDstIn_Mode &&
1830 xfermode != SkXfermode::kSrcOut_Mode &&
1831 xfermode != SkXfermode::kDstOut_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001832 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001833 return;
1834 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001835
1836 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001837 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001838 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001839 // We have to make a copy of these here because changing the current
1840 // content into a form xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001841 SkClipStack clipStack = contentEntries->fState.fClipStack;
1842 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001843
reed@google.comfc641d02012-09-20 17:52:20 +00001844 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001845 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001846 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001847 }
1848
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001849 drawFormXObjectWithClip(dst, &clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001850
1851 // We've redrawn dst minus the clip area, if there's no src, we're done.
1852 if (!srcFormXObject.get()) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001853 return;
1854 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001855
1856 SkMatrix identity;
1857 identity.reset();
1858 SkPaint stockPaint;
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001859 ScopedContentEntry inClipContentEntry(this, &fExistingClipStack,
1860 fExistingClipRegion, identity,
1861 stockPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001862 if (!inClipContentEntry.entry()) {
1863 return;
1864 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001865
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001866 SkAutoTUnref<SkPDFGraphicState> sMaskGS;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001867 if (xfermode == SkXfermode::kSrcIn_Mode ||
1868 xfermode == SkXfermode::kSrcOut_Mode) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001869 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001870 dst,
1871 xfermode == SkXfermode::kSrcOut_Mode,
1872 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001873 fXObjectResources.push(srcFormXObject.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001874 srcFormXObject.get()->ref();
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001875 } else {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001876 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001877 srcFormXObject.get(),
1878 xfermode == SkXfermode::kDstOut_Mode,
1879 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001880 // dst already added to fXObjectResources in drawFormXObjectWithClip.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001881 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001882 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001883 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001884
1885 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001886 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001887
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001888 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001889 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001890 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001891}
1892
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001893bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001894 ContentEntry* contentEntries = getContentEntries()->get();
1895 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1896 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001897 return true;
1898 }
1899 return false;
1900}
1901
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001902void SkPDFDevice::populateGraphicStateEntryFromPaint(
1903 const SkMatrix& matrix,
1904 const SkClipStack& clipStack,
1905 const SkRegion& clipRegion,
1906 const SkPaint& paint,
1907 bool hasText,
1908 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001909 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001910
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001911 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1912 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001913
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001914 entry->fMatrix = matrix;
1915 entry->fClipStack = clipStack;
1916 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001917 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1918 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001919
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001920 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001921 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001922 const SkShader* shader = paint.getShader();
1923 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001924 if (shader) {
1925 // PDF positions patterns relative to the initial transform, so
1926 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001927 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001928 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001929
1930 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001931 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001932 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001933
1934 // We need to apply the initial transform to bounds in order to get
1935 // bounds in a consistent coordinate system.
1936 SkRect boundsTemp;
1937 boundsTemp.set(bounds);
1938 fInitialTransform.mapRect(&boundsTemp);
1939 boundsTemp.roundOut(&bounds);
1940
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001941 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001942
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001943 if (pdfShader.get()) {
1944 // pdfShader has been canonicalized so we can directly compare
1945 // pointers.
1946 int resourceIndex = fShaderResources.find(pdfShader.get());
1947 if (resourceIndex < 0) {
1948 resourceIndex = fShaderResources.count();
1949 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001950 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001951 }
1952 entry->fShaderIndex = resourceIndex;
1953 } else {
1954 // A color shader is treated as an invalid shader so we don't have
1955 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001956 SkShader::GradientInfo gradientInfo;
1957 SkColor gradientColor;
1958 gradientInfo.fColors = &gradientColor;
1959 gradientInfo.fColorOffsets = NULL;
1960 gradientInfo.fColorCount = 1;
1961 if (shader->asAGradient(&gradientInfo) ==
1962 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001963 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1964 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001965 }
1966 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001967 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001968
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001969 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001970 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001971 newGraphicState.reset(
1972 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001973 } else {
1974 SkPaint newPaint = paint;
1975 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001976 newGraphicState.reset(
1977 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001978 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001979 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001980 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001981
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001982 if (hasText) {
1983 entry->fTextScaleX = paint.getTextScaleX();
1984 entry->fTextFill = paint.getStyle();
1985 } else {
1986 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001987 }
1988}
1989
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001990int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
1991 // Assumes that gs has been canonicalized (so we can directly compare
1992 // pointers).
1993 int result = fGraphicStateResources.find(gs);
1994 if (result < 0) {
1995 result = fGraphicStateResources.count();
1996 fGraphicStateResources.push(gs);
1997 gs->ref();
1998 }
1999 return result;
2000}
2001
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002002void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2003 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002004 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002005 if (contentEntry->fState.fFont == NULL ||
2006 contentEntry->fState.fTextSize != paint.getTextSize() ||
2007 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002008 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002009 contentEntry->fContent.writeText("/");
2010 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2011 SkPDFResourceDict::kFont_ResourceType,
2012 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002013 contentEntry->fContent.writeText(" ");
2014 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2015 contentEntry->fContent.writeText(" Tf\n");
2016 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002017 }
2018}
2019
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002020int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002021 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002022 int resourceIndex = fFontResources.find(newFont.get());
2023 if (resourceIndex < 0) {
2024 resourceIndex = fFontResources.count();
2025 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002026 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002027 }
2028 return resourceIndex;
2029}
2030
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002031void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002032 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002033 const SkRegion& origClipRegion,
2034 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002035 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002036 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002037 SkMatrix matrix = origMatrix;
2038 SkRegion perspectiveBounds;
2039 const SkRegion* clipRegion = &origClipRegion;
2040 SkBitmap perspectiveBitmap;
2041 const SkBitmap* bitmap = &origBitmap;
2042 SkBitmap tmpSubsetBitmap;
2043
2044 // Rasterize the bitmap using perspective in a new bitmap.
2045 if (origMatrix.hasPerspective()) {
2046 SkBitmap* subsetBitmap;
2047 if (srcRect) {
2048 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2049 return;
2050 }
2051 subsetBitmap = &tmpSubsetBitmap;
2052 } else {
2053 subsetBitmap = &tmpSubsetBitmap;
2054 *subsetBitmap = origBitmap;
2055 }
2056 srcRect = NULL;
2057
2058 // Transform the bitmap in the new space.
2059 SkPath perspectiveOutline;
2060 perspectiveOutline.addRect(
2061 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2062 SkIntToScalar(subsetBitmap->height())));
2063 perspectiveOutline.transform(origMatrix);
2064
2065 // TODO(edisonn): perf - use current clip too.
2066 // Retrieve the bounds of the new shape.
2067 SkRect bounds = perspectiveOutline.getBounds();
2068
2069 // TODO(edisonn): add DPI settings. Currently 1 pixel/point, which does
2070 // not look great, but it is not producing large PDFs.
2071
2072 // TODO(edisonn): A better approach would be to use a bitmap shader
2073 // (in clamp mode) and draw a rect over the entire bounding box. Then
2074 // intersect perspectiveOutline to the clip. That will avoid introducing
2075 // alpha to the image while still giving good behavior at the edge of
2076 // the image. Avoiding alpha will reduce the pdf size and generation
2077 // CPU time some.
2078
2079 perspectiveBitmap.setConfig(SkBitmap::kARGB_8888_Config,
2080 SkScalarCeilToInt(bounds.width()),
2081 SkScalarCeilToInt(bounds.height()));
2082 perspectiveBitmap.allocPixels();
2083 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2084
2085 SkBitmapDevice device(perspectiveBitmap);
2086 SkCanvas canvas(&device);
2087
2088 SkScalar deltaX = bounds.left();
2089 SkScalar deltaY = bounds.top();
2090
2091 SkMatrix offsetMatrix = origMatrix;
2092 offsetMatrix.postTranslate(-deltaX, -deltaY);
2093
2094 // Translate the draw in the new canvas, so we perfectly fit the
2095 // shape in the bitmap.
2096 canvas.setMatrix(offsetMatrix);
2097
2098 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2099
2100 // Make sure the final bits are in the bitmap.
2101 canvas.flush();
2102
2103 // In the new space, we use the identity matrix translated.
2104 matrix.setTranslate(deltaX, deltaY);
2105 perspectiveBounds.setRect(
2106 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2107 SkScalarFloorToInt(bounds.y()),
2108 SkScalarCeilToInt(bounds.width()),
2109 SkScalarCeilToInt(bounds.height())));
2110 clipRegion = &perspectiveBounds;
2111 srcRect = NULL;
2112 bitmap = &perspectiveBitmap;
2113 }
2114
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002115 SkMatrix scaled;
2116 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002117 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2118 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002119 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002120 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002121 scaled.postScale(SkIntToScalar(subset.width()),
2122 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002123 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002124 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002125 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002126 return;
2127 }
2128
2129 if (srcRect && !subset.intersect(*srcRect)) {
2130 return;
2131 }
2132
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002133 SkPDFImage* image = SkPDFImage::CreateImage(*bitmap, subset, fEncoder);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002134 if (!image) {
2135 return;
2136 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002137
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002138 fXObjectResources.push(image); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002139 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002140 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002141}
reed@google.com982cb872011-12-07 18:34:08 +00002142
2143bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2144 SkCanvas::Config8888) {
2145 return false;
2146}
reed@google.comb55deeb2012-01-06 14:43:09 +00002147
2148bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2149 return false;
2150}