blob: 1aed85632a7b978688d388f2641c8cd1431daf14 [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),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000707 fEncoder(NULL),
708 fRasterDpi(SkFloatToScalar(72.0f)) {
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000709 // just report that PDF does not supports perspective
710 // TODO(edisonn): update the shape when possible
711 // or dump in an image otherwise
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000712 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
713
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000714 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000715 // origin at the bottom left. This matrix corrects for that. But that only
716 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000717 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
718 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000719 fInitialTransform.preConcat(initialTransform);
720
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000721 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000722 fExistingClipRegion.setRect(existingClip);
723
724 this->init();
725}
726
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000727// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000728SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
729 const SkClipStack& existingClipStack,
730 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000731 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000732 fPageSize(layerSize),
733 fContentSize(layerSize),
734 fExistingClipStack(existingClipStack),
735 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000736 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000737 fLastMarginContentEntry(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000738 fClipStack(NULL),
739 fEncoder(NULL),
740 fRasterDpi(SkFloatToScalar(72.0f)) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000741 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000742 this->init();
743}
744
745SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000746 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000747}
748
749void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000750 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000751 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000752 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000753 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000754 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000755 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000756 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000757 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000758 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
759 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000760}
761
vandebo@chromium.org98594282011-07-25 22:34:12 +0000762void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000763 fGraphicStateResources.unrefAll();
764 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000765 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000766 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000767 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000768 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000769 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000770
vandebo@chromium.org98594282011-07-25 22:34:12 +0000771 if (clearFontUsage) {
772 fFontGlyphUsage->reset();
773 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000774}
775
reed@google.com982cb872011-12-07 18:34:08 +0000776uint32_t SkPDFDevice::getDeviceCapabilities() {
777 return kVector_Capability;
778}
779
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000780void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000781 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000782 this->init();
783
784 SkPaint paint;
785 paint.setColor(color);
786 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000787 SkMatrix identity;
788 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000789 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
790 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000791 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000792}
793
794void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000795 SkPaint newPaint = paint;
796 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000797 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000798 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000799}
800
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000801void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
802 ContentEntry* contentEntry) {
803 if (!contentEntry) {
804 return;
805 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000806 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
807 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000808 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000809 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000810 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000811 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000812 inverse.mapRect(&bbox);
813
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000814 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000815 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000816 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000817}
818
819void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
820 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000821 const SkPaint& passedPaint) {
822 if (count == 0) {
823 return;
824 }
825
epoger@google.comb58772f2013-03-08 09:09:10 +0000826 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
827 return;
828 }
829
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000830 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
831 // We only use this when there's a path effect because of the overhead
832 // of multiple calls to setUpContentEntry it causes.
833 if (passedPaint.getPathEffect()) {
834 if (d.fClip->isEmpty()) {
835 return;
836 }
837 SkDraw pointDraw(d);
838 pointDraw.fDevice = this;
839 pointDraw.drawPoints(mode, count, points, passedPaint, true);
840 return;
841 }
842
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000843 const SkPaint* paint = &passedPaint;
844 SkPaint modifiedPaint;
845
846 if (mode == SkCanvas::kPoints_PointMode &&
847 paint->getStrokeCap() != SkPaint::kRound_Cap) {
848 modifiedPaint = *paint;
849 paint = &modifiedPaint;
850 if (paint->getStrokeWidth()) {
851 // PDF won't draw a single point with square/butt caps because the
852 // orientation is ambiguous. Draw a rectangle instead.
853 modifiedPaint.setStyle(SkPaint::kFill_Style);
854 SkScalar strokeWidth = paint->getStrokeWidth();
855 SkScalar halfStroke = SkScalarHalf(strokeWidth);
856 for (size_t i = 0; i < count; i++) {
857 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
858 r.inset(-halfStroke, -halfStroke);
859 drawRect(d, r, modifiedPaint);
860 }
861 return;
862 } else {
863 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
864 }
865 }
866
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000867 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000868 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000869 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000870 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000871
872 switch (mode) {
873 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000874 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000875 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000876 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000877 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000878 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000879 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000880 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000881 break;
882 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000883 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000884 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000885 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000886 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000887 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000888 &content.entry()->fContent);
889 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000890 }
891 break;
892 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000893 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
894 for (size_t i = 0; i < count; i++) {
895 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000896 &content.entry()->fContent);
897 SkPDFUtils::ClosePath(&content.entry()->fContent);
898 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000899 }
900 break;
901 default:
902 SkASSERT(false);
903 }
904}
905
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000906void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000907 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000908 SkRect r = rect;
909 r.sort();
910
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000911 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000912 if (d.fClip->isEmpty()) {
913 return;
914 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000915 SkPath path;
916 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000917 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000918 return;
919 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000920
epoger@google.comb58772f2013-03-08 09:09:10 +0000921 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000922 return;
923 }
924
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000925 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000926 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000927 return;
928 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000929 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000930 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000931 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000932}
933
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000934void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000935 const SkPaint& paint, const SkMatrix* prePathMatrix,
936 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000937 SkPath modifiedPath;
938 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
939
940 SkMatrix matrix = *d.fMatrix;
941 if (prePathMatrix) {
942 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
943 if (!pathIsMutable) {
944 pathPtr = &modifiedPath;
945 pathIsMutable = true;
946 }
947 origPath.transform(*prePathMatrix, pathPtr);
948 } else {
949 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000950 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000951 return;
952 }
953 }
954 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000955
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000956 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000957 if (d.fClip->isEmpty()) {
958 return;
959 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000960 if (!pathIsMutable) {
961 pathPtr = &modifiedPath;
962 pathIsMutable = true;
963 }
964 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000965
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000966 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000967 noEffectPaint.setPathEffect(NULL);
968 if (fill) {
969 noEffectPaint.setStyle(SkPaint::kFill_Style);
970 } else {
971 noEffectPaint.setStyle(SkPaint::kStroke_Style);
972 noEffectPaint.setStrokeWidth(0);
973 }
974 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000975 return;
976 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000977
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000978#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000979 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000980 return;
981 }
982#endif
983
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000984 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000985 return;
986 }
987
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000988 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000989 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000990 return;
991 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000992 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
993 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000994 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000995 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000996}
997
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000998void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
999 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001000 const SkPaint& paint,
1001 SkCanvas::DrawBitmapRectFlags flags) {
1002 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001003 SkMatrix matrix;
1004 SkRect bitmapBounds, tmpSrc, tmpDst;
1005 SkBitmap tmpBitmap;
1006
1007 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1008
1009 // Compute matrix from the two rectangles
1010 if (src) {
1011 tmpSrc = *src;
1012 } else {
1013 tmpSrc = bitmapBounds;
1014 }
1015 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1016
1017 const SkBitmap* bitmapPtr = &bitmap;
1018
1019 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1020 // needed (if the src was clipped). No check needed if src==null.
1021 if (src) {
1022 if (!bitmapBounds.contains(*src)) {
1023 if (!tmpSrc.intersect(bitmapBounds)) {
1024 return; // nothing to draw
1025 }
1026 // recompute dst, based on the smaller tmpSrc
1027 matrix.mapRect(&tmpDst, tmpSrc);
1028 }
1029
1030 // since we may need to clamp to the borders of the src rect within
1031 // the bitmap, we extract a subset.
1032 // TODO: make sure this is handled in drawBitmap and remove from here.
1033 SkIRect srcIR;
1034 tmpSrc.roundOut(&srcIR);
1035 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1036 return;
1037 }
1038 bitmapPtr = &tmpBitmap;
1039
1040 // Since we did an extract, we need to adjust the matrix accordingly
1041 SkScalar dx = 0, dy = 0;
1042 if (srcIR.fLeft > 0) {
1043 dx = SkIntToScalar(srcIR.fLeft);
1044 }
1045 if (srcIR.fTop > 0) {
1046 dy = SkIntToScalar(srcIR.fTop);
1047 }
1048 if (dx || dy) {
1049 matrix.preTranslate(dx, dy);
1050 }
1051 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001052 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001053}
1054
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001055void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001056 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001057 if (d.fClip->isEmpty()) {
1058 return;
1059 }
1060
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001061 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001062 transform.postConcat(*d.fMatrix);
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001063 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001064}
1065
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001066void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001067 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001068 if (d.fClip->isEmpty()) {
1069 return;
1070 }
1071
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001072 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001073 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001074 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001075}
1076
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001077void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001078 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001079 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1080 if (paint.getMaskFilter() != NULL) {
1081 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1082 // making text unreadable (e.g. same text twice when using CSS shadows).
1083 return;
1084 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001085 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001086 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001087 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001088 return;
1089 }
1090
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001091 SkGlyphStorage storage(0);
1092 uint16_t* glyphIDs = NULL;
1093 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1094 &glyphIDs);
1095 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001096
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001097 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001098 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001099 content.entry()->fContent.writeText("BT\n");
1100 set_text_transform(x, y, textPaint.getTextSkewX(),
1101 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001102 size_t consumedGlyphCount = 0;
1103 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001104 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1105 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001106 size_t availableGlyphs =
1107 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1108 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001109 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1110 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001111 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001112 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001113 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001114 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001115 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001116 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001117 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001118 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001119}
1120
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001121void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001122 const SkScalar pos[], SkScalar constY,
1123 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001124 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1125 if (paint.getMaskFilter() != NULL) {
1126 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1127 // making text unreadable (e.g. same text twice when using CSS shadows).
1128 return;
1129 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001130 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001131 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001132 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001133 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001134 return;
1135 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001136
djsollen@google.com5df5e612013-10-03 14:42:24 +00001137#ifdef SK_BUILD_FOR_ANDROID
1138 /*
1139 * In the case that we have enabled fallback fonts on Android we need to
1140 * take the following steps to ensure that the PDF draws all characters,
1141 * regardless of their underlying font file, correctly.
1142 *
1143 * 1. Convert input into GlyphID encoding if it currently is not
1144 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1145 * glyph resolves to
1146 * 3. Iterate over those typefaces and recursively call this function with
1147 * only the glyphs (and their positions) that the typeface is capable of
1148 * resolving.
1149 */
1150 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1151 uint16_t* glyphIDs = NULL;
1152 SkGlyphStorage tmpStorage(0);
1153 size_t numGlyphs = 0;
1154
1155 // convert to glyphIDs
1156 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1157 numGlyphs = len / 2;
1158 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1159 } else {
1160 numGlyphs = paint.textToGlyphs(text, len, NULL);
1161 tmpStorage.reset(numGlyphs);
1162 paint.textToGlyphs(text, len, tmpStorage.get());
1163 glyphIDs = tmpStorage.get();
1164 }
1165
1166 // if no typeface is provided in the paint get the default
1167 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1168 if (NULL == origFace.get()) {
1169 origFace.reset(SkTypeface::RefDefault());
1170 }
1171 const uint16_t origGlyphCount = origFace->countGlyphs();
1172
1173 // keep a list of the already visited typefaces and some data about them
1174 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1175
1176 // find all the typefaces needed to resolve this run of text
1177 bool usesOriginalTypeface = false;
1178 for (uint16_t x = 0; x < numGlyphs; ++x) {
1179 // optimization that checks to see if original typeface can resolve the glyph
1180 if (glyphIDs[x] < origGlyphCount) {
1181 usesOriginalTypeface = true;
1182 continue;
1183 }
1184
1185 // find the fallback typeface that supports this glyph
1186 TypefaceFallbackData data;
1187 data.typeface = SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1188 paint.getPaintOptionsAndroid(),
1189 &data.lowerBounds, &data.upperBounds);
1190 // add the typeface and its data if we don't have it
1191 if (data.typeface && !visitedTypefaces.contains(data)) {
1192 visitedTypefaces.push(data);
1193 }
1194 }
1195
1196 // if the original font was used then add it to the list as well
1197 if (usesOriginalTypeface) {
1198 TypefaceFallbackData* data = visitedTypefaces.push();
1199 data->typeface = origFace.get();
1200 data->lowerBounds = 0;
1201 data->upperBounds = origGlyphCount;
1202 }
1203
1204 // keep a scratch glyph and pos storage
1205 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1206 SkScalar* tmpPos = posStorage.get();
1207 SkGlyphStorage glyphStorage(numGlyphs);
1208 uint16_t* tmpGlyphIDs = glyphStorage.get();
1209
1210 // loop through all the valid typefaces, trim the glyphs to only those
1211 // resolved by the typeface, and then draw that run of glyphs
1212 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1213 const TypefaceFallbackData& data = visitedTypefaces[x];
1214
1215 int tmpGlyphCount = 0;
1216 for (uint16_t y = 0; y < numGlyphs; ++y) {
1217 if (glyphIDs[y] >= data.lowerBounds && glyphIDs[y] < data.upperBounds) {
1218 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1219 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1220 &(pos[y * scalarsPerPos]),
1221 scalarsPerPos * sizeof(SkScalar));
1222 tmpGlyphCount++;
1223 }
1224 }
1225
1226 // recursively call this function with the right typeface
1227 SkPaint tmpPaint = paint;
1228 tmpPaint.setTypeface(data.typeface);
1229 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1230
1231 // turn off fallback chaining
1232 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1233 paintOpts.setUseFontFallbacks(false);
1234 tmpPaint.setPaintOptionsAndroid(paintOpts);
1235
1236 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1237 scalarsPerPos, tmpPaint);
1238 }
1239 return;
1240 }
1241#endif
1242
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001243 SkGlyphStorage storage(0);
1244 uint16_t* glyphIDs = NULL;
1245 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1246 &glyphIDs);
1247 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001248
1249 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001250 content.entry()->fContent.writeText("BT\n");
1251 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001252 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001253 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001254 uint16_t encodedValue = glyphIDs[i];
1255 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001256 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001257 i--;
1258 continue;
1259 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001260 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001261 SkScalar x = pos[i * scalarsPerPos];
1262 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001263 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001264 set_text_transform(x, y, textPaint.getTextSkewX(),
1265 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001266 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001267 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001268 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001269 content.entry()->fContent.writeText(encodedString.c_str());
1270 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001271 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001272 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001273}
1274
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001275void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001276 const SkPath& path, const SkMatrix* matrix,
1277 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001278 if (d.fClip->isEmpty()) {
1279 return;
1280 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001281 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001282}
1283
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001284void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001285 int vertexCount, const SkPoint verts[],
1286 const SkPoint texs[], const SkColor colors[],
1287 SkXfermode* xmode, const uint16_t indices[],
1288 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001289 if (d.fClip->isEmpty()) {
1290 return;
1291 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001292 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001293}
1294
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001295void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device, int x, int y,
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001296 const SkPaint& paint) {
1297 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1298 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001299 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001300 return;
1301 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001302
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001303 // Assume that a vector capable device means that it's a PDF Device.
1304 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001305 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001306 return;
1307 }
1308
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001309 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001310 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001311 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001312 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001313 return;
1314 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001315
1316 SkPDFFormXObject* xobject = new SkPDFFormXObject(pdfDevice);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001317 fXObjectResources.push(xobject); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001318 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001319 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001320
1321 // Merge glyph sets from the drawn device.
1322 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001323}
1324
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001325void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1326 INHERITED::onAttachToCanvas(canvas);
1327
1328 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1329 fClipStack = canvas->getClipStack();
1330}
1331
1332void SkPDFDevice::onDetachFromCanvas() {
1333 INHERITED::onDetachFromCanvas();
1334
1335 fClipStack = NULL;
1336}
1337
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001338ContentEntry* SkPDFDevice::getLastContentEntry() {
1339 if (fDrawingArea == kContent_DrawingArea) {
1340 return fLastContentEntry;
1341 } else {
1342 return fLastMarginContentEntry;
1343 }
1344}
1345
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001346SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001347 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001348 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001349 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001350 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001351 }
1352}
1353
1354void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1355 if (fDrawingArea == kContent_DrawingArea) {
1356 fLastContentEntry = contentEntry;
1357 } else {
1358 fLastMarginContentEntry = contentEntry;
1359 }
1360}
1361
1362void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001363 // A ScopedContentEntry only exists during the course of a draw call, so
1364 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001365 fDrawingArea = drawingArea;
1366}
1367
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001368SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001369 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001370 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001371
1372 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001373 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001374 fResourceDict->insertResourceAsReference(
1375 SkPDFResourceDict::kExtGState_ResourceType,
1376 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001377 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001378 }
1379
1380 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001381 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001382 fResourceDict->insertResourceAsReference(
1383 SkPDFResourceDict::kXObject_ResourceType,
1384 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001385 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001386 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001387
1388 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001389 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001390 fResourceDict->insertResourceAsReference(
1391 SkPDFResourceDict::kFont_ResourceType,
1392 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001393 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001394 }
1395
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001396 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001397 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001398 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001399 fResourceDict->insertResourceAsReference(
1400 SkPDFResourceDict::kPattern_ResourceType,
1401 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001402 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001403 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001404 }
1405 return fResourceDict;
1406}
1407
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001408const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1409 return fFontResources;
1410}
1411
reed@google.com2a006c12012-09-19 17:05:55 +00001412SkPDFArray* SkPDFDevice::copyMediaBox() const {
1413 // should this be a singleton?
1414 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001415
reed@google.com2a006c12012-09-19 17:05:55 +00001416 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001417 mediaBox->reserve(4);
1418 mediaBox->append(zero.get());
1419 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001420 mediaBox->appendInt(fPageSize.fWidth);
1421 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001422 return mediaBox;
1423}
1424
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001425SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001426 SkMemoryStream* result = new SkMemoryStream;
1427 result->setData(this->copyContentToData())->unref();
1428 return result;
1429}
1430
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001431void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1432 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001433 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1434 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001435 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001436 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001437 SkPoint translation;
1438 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001439 translation.negate();
1440 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1441 translation);
1442 gsState.updateMatrix(entry->fState.fMatrix);
1443 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001444
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001445 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001446 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001447 entry = entry->fNext.get();
1448 }
1449 gsState.drainStack();
1450}
1451
reed@google.com5667afc2011-06-27 14:42:15 +00001452SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001453 SkDynamicMemoryWStream data;
1454 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1455 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001456 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001457
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001458 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1459 // colors the contentArea white before it starts drawing into it and
1460 // that currently acts as our clip.
1461 // Also, think about adding a transform here (or assume that the values
1462 // sent across account for that)
1463 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001464
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001465 // If the content area is the entire page, then we don't need to clip
1466 // the content area (PDF area clips to the page size). Otherwise,
1467 // we have to clip to the content area; we've already applied the
1468 // initial transform, so just clip to the device size.
1469 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001470 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1471 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001472 emit_clip(NULL, &r, &data);
1473 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001474
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001475 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001476
reed@google.com5667afc2011-06-27 14:42:15 +00001477 // potentially we could cache this SkData, and only rebuild it if we
1478 // see that our state has changed.
1479 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001480}
1481
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001482#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001483/* Draws an inverse filled path by using Path Ops to compute the positive
1484 * inverse using the current clip as the inverse bounds.
1485 * Return true if this was an inverse path and was properly handled,
1486 * otherwise returns false and the normal drawing routine should continue,
1487 * either as a (incorrect) fallback or because the path was not inverse
1488 * in the first place.
1489 */
1490bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001491 const SkPaint& paint, bool pathIsMutable,
1492 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001493 if (!origPath.isInverseFillType()) {
1494 return false;
1495 }
1496
1497 if (d.fClip->isEmpty()) {
1498 return false;
1499 }
1500
1501 SkPath modifiedPath;
1502 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1503 SkPaint noInversePaint(paint);
1504
1505 // Merge stroking operations into final path.
1506 if (SkPaint::kStroke_Style == paint.getStyle() ||
1507 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1508 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1509 if (doFillPath) {
1510 noInversePaint.setStyle(SkPaint::kFill_Style);
1511 noInversePaint.setStrokeWidth(0);
1512 pathPtr = &modifiedPath;
1513 } else {
1514 // To be consistent with the raster output, hairline strokes
1515 // are rendered as non-inverted.
1516 modifiedPath.toggleInverseFillType();
1517 drawPath(d, modifiedPath, paint, NULL, true);
1518 return true;
1519 }
1520 }
1521
1522 // Get bounds of clip in current transform space
1523 // (clip bounds are given in device space).
1524 SkRect bounds;
1525 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001526 SkMatrix totalMatrix = *d.fMatrix;
1527 if (prePathMatrix) {
1528 totalMatrix.preConcat(*prePathMatrix);
1529 }
1530 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001531 return false;
1532 }
1533 bounds.set(d.fClip->getBounds());
1534 transformInverse.mapRect(&bounds);
1535
1536 // Extend the bounds by the line width (plus some padding)
1537 // so the edge doesn't cause a visible stroke.
1538 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1539 paint.getStrokeWidth() + SK_Scalar1);
1540
1541 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1542 return false;
1543 }
1544
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001545 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001546 return true;
1547}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001548#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001549
epoger@google.comb58772f2013-03-08 09:09:10 +00001550bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1551 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001552 SkAnnotation* annotationInfo = p.getAnnotation();
1553 if (!annotationInfo) {
1554 return false;
1555 }
1556 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001557 if (urlData) {
1558 handleLinkToURL(urlData, r, matrix);
1559 return p.isNoDrawAnnotation();
1560 }
1561 SkData* linkToName = annotationInfo->find(SkAnnotationKeys::Link_Named_Dest_Key());
1562 if (linkToName) {
1563 handleLinkToNamedDest(linkToName, r, matrix);
1564 return p.isNoDrawAnnotation();
1565 }
1566 return false;
1567}
1568
1569bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1570 const SkMatrix& matrix,
1571 const SkPaint& paint) {
1572 SkAnnotation* annotationInfo = paint.getAnnotation();
1573 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001574 return false;
1575 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001576 SkData* nameData = annotationInfo->find(SkAnnotationKeys::Define_Named_Dest_Key());
1577 if (nameData) {
1578 for (size_t i = 0; i < count; i++) {
1579 defineNamedDestination(nameData, points[i], matrix);
1580 }
1581 return paint.isNoDrawAnnotation();
1582 }
1583 return false;
1584}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001585
epoger@google.comb58772f2013-03-08 09:09:10 +00001586SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r, const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001587 SkMatrix transform = matrix;
1588 transform.postConcat(fInitialTransform);
1589 SkRect translatedRect;
1590 transform.mapRect(&translatedRect, r);
1591
reed@google.com2a006c12012-09-19 17:05:55 +00001592 if (NULL == fAnnotations) {
1593 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001594 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001595 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001596 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001597 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001598
epoger@google.comb58772f2013-03-08 09:09:10 +00001599 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001600 border->reserve(3);
1601 border->appendInt(0); // Horizontal corner radius.
1602 border->appendInt(0); // Vertical corner radius.
1603 border->appendInt(0); // Width, 0 = no border.
1604 annotation->insert("Border", border.get());
1605
epoger@google.comb58772f2013-03-08 09:09:10 +00001606 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001607 rect->reserve(4);
1608 rect->appendScalar(translatedRect.fLeft);
1609 rect->appendScalar(translatedRect.fTop);
1610 rect->appendScalar(translatedRect.fRight);
1611 rect->appendScalar(translatedRect.fBottom);
1612 annotation->insert("Rect", rect.get());
1613
epoger@google.comb58772f2013-03-08 09:09:10 +00001614 return annotation;
1615}
epoger@google.com1cad8982013-03-06 00:05:13 +00001616
epoger@google.comb58772f2013-03-08 09:09:10 +00001617void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1618 const SkMatrix& matrix) {
1619 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1620
1621 SkString url(static_cast<const char *>(urlData->data()),
1622 urlData->size() - 1);
1623 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1624 action->insertName("S", "URI");
1625 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1626 annotation->insert("A", action.get());
1627}
1628
1629void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1630 const SkMatrix& matrix) {
1631 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1632 SkString name(static_cast<const char *>(nameData->data()),
1633 nameData->size() - 1);
1634 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1635}
1636
1637struct NamedDestination {
1638 const SkData* nameData;
1639 SkPoint point;
1640
1641 NamedDestination(const SkData* nameData, const SkPoint& point)
1642 : nameData(nameData), point(point) {
1643 nameData->ref();
1644 }
1645
1646 ~NamedDestination() {
1647 nameData->unref();
1648 }
1649};
1650
1651void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1652 const SkMatrix& matrix) {
1653 SkMatrix transform = matrix;
1654 transform.postConcat(fInitialTransform);
1655 SkPoint translatedPoint;
1656 transform.mapXY(point.x(), point.y(), &translatedPoint);
1657 fNamedDestinations.push(
1658 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1659}
1660
1661void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1662 int nDest = fNamedDestinations.count();
1663 for (int i = 0; i < nDest; i++) {
1664 NamedDestination* dest = fNamedDestinations[i];
1665 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1666 pdfDest->reserve(5);
1667 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1668 pdfDest->appendName("XYZ");
1669 pdfDest->appendScalar(dest->point.x());
1670 pdfDest->appendScalar(dest->point.y());
1671 pdfDest->appendInt(0); // Leave zoom unchanged
1672 dict->insert(static_cast<const char *>(dest->nameData->data()), pdfDest);
1673 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001674}
1675
reed@google.comfc641d02012-09-20 17:52:20 +00001676SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1677 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001678 // We always draw the form xobjects that we create back into the device, so
1679 // we simply preserve the font usage instead of pulling it out and merging
1680 // it back in later.
1681 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001682 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001683 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001684}
1685
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001686void SkPDFDevice::clearClipFromContent(const SkClipStack* clipStack,
1687 const SkRegion& clipRegion) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001688 if (clipRegion.isEmpty() || isContentEmpty()) {
1689 return;
1690 }
reed@google.comfc641d02012-09-20 17:52:20 +00001691 SkAutoTUnref<SkPDFFormXObject> curContent(createFormXObjectFromDevice());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001692
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001693 // Redraw what we already had, but with the clip as a mask.
reed@google.comfc641d02012-09-20 17:52:20 +00001694 drawFormXObjectWithClip(curContent, clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001695}
1696
1697void SkPDFDevice::drawFormXObjectWithClip(SkPDFFormXObject* xobject,
1698 const SkClipStack* clipStack,
1699 const SkRegion& clipRegion,
1700 bool invertClip) {
1701 if (clipRegion.isEmpty() && !invertClip) {
1702 return;
1703 }
1704
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001705 // Create the mask.
1706 SkMatrix identity;
1707 identity.reset();
1708 SkDraw draw;
1709 draw.fMatrix = &identity;
1710 draw.fClip = &clipRegion;
1711 draw.fClipStack = clipStack;
1712 SkPaint stockPaint;
1713 this->drawPaint(draw, stockPaint);
reed@google.comfc641d02012-09-20 17:52:20 +00001714 SkAutoTUnref<SkPDFFormXObject> maskFormXObject(createFormXObjectFromDevice());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001715 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001716 SkPDFGraphicState::GetSMaskGraphicState(maskFormXObject, invertClip,
1717 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001718
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001719 // Draw the xobject with the clip as a mask.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001720 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001721 identity, stockPaint);
1722 if (!content.entry()) {
1723 return;
1724 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001725 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001726 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001727 SkPDFUtils::DrawFormXObject(fXObjectResources.count(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001728 &content.entry()->fContent);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001729 fXObjectResources.push(xobject);
1730 xobject->ref();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001731
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001732 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001733 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001734 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001735}
1736
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001737ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1738 const SkRegion& clipRegion,
1739 const SkMatrix& matrix,
1740 const SkPaint& paint,
1741 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001742 SkPDFFormXObject** dst) {
1743 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001744 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001745 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001746 }
1747
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001748 // The clip stack can come from an SkDraw where it is technically optional.
1749 SkClipStack synthesizedClipStack;
1750 if (clipStack == NULL) {
1751 if (clipRegion == fExistingClipRegion) {
1752 clipStack = &fExistingClipStack;
1753 } else {
1754 // GraphicStackState::updateClip expects the clip stack to have
1755 // fExistingClip as a prefix, so start there, then set the clip
1756 // to the passed region.
1757 synthesizedClipStack = fExistingClipStack;
1758 SkPath clipPath;
1759 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001760 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1761 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001762 clipStack = &synthesizedClipStack;
1763 }
1764 }
1765
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001766 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1767 if (paint.getXfermode()) {
1768 paint.getXfermode()->asMode(&xfermode);
1769 }
1770
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001771 if (xfermode == SkXfermode::kClear_Mode ||
1772 xfermode == SkXfermode::kSrc_Mode) {
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001773 this->clearClipFromContent(clipStack, clipRegion);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001774 } else if (xfermode == SkXfermode::kSrcIn_Mode ||
1775 xfermode == SkXfermode::kDstIn_Mode ||
1776 xfermode == SkXfermode::kSrcOut_Mode ||
1777 xfermode == SkXfermode::kDstOut_Mode) {
1778 // For the following modes, we use both source and destination, but
1779 // we use one as a smask for the other, so we have to make form xobjects
1780 // out of both of them: SrcIn, DstIn, SrcOut, DstOut.
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001781 if (isContentEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001782 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001783 } else {
reed@google.comfc641d02012-09-20 17:52:20 +00001784 *dst = createFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001785 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001786 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001787 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001788 // SrcAtop, DestAtop, Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001789
1790 // These xfer modes don't draw source at all.
1791 if (xfermode == SkXfermode::kClear_Mode ||
1792 xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001793 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001794 }
1795
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001796 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001797 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001798
1799 ContentEntry* lastContentEntry = getLastContentEntry();
1800 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1801 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001802 } else {
1803 newEntry.reset(new ContentEntry);
1804 entry = newEntry.get();
1805 }
1806
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001807 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001808 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001809 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1810 entry->fState.compareInitialState(lastContentEntry->fState)) {
1811 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001812 }
1813
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001814 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001815 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001816 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001817 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001818 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001819 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001820 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001821 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001822 lastContentEntry->fNext.reset(entry);
1823 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001824 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001825 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001826 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001827}
1828
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001829void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
1830 SkPDFFormXObject* dst) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001831 if (xfermode != SkXfermode::kSrcIn_Mode &&
1832 xfermode != SkXfermode::kDstIn_Mode &&
1833 xfermode != SkXfermode::kSrcOut_Mode &&
1834 xfermode != SkXfermode::kDstOut_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001835 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001836 return;
1837 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001838
1839 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001840 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001841 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001842 // We have to make a copy of these here because changing the current
1843 // content into a form xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001844 SkClipStack clipStack = contentEntries->fState.fClipStack;
1845 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001846
reed@google.comfc641d02012-09-20 17:52:20 +00001847 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001848 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001849 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001850 }
1851
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001852 drawFormXObjectWithClip(dst, &clipStack, clipRegion, true);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001853
1854 // We've redrawn dst minus the clip area, if there's no src, we're done.
1855 if (!srcFormXObject.get()) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001856 return;
1857 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001858
1859 SkMatrix identity;
1860 identity.reset();
1861 SkPaint stockPaint;
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001862 ScopedContentEntry inClipContentEntry(this, &fExistingClipStack,
1863 fExistingClipRegion, identity,
1864 stockPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001865 if (!inClipContentEntry.entry()) {
1866 return;
1867 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001868
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001869 SkAutoTUnref<SkPDFGraphicState> sMaskGS;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001870 if (xfermode == SkXfermode::kSrcIn_Mode ||
1871 xfermode == SkXfermode::kSrcOut_Mode) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001872 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001873 dst,
1874 xfermode == SkXfermode::kSrcOut_Mode,
1875 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001876 fXObjectResources.push(srcFormXObject.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001877 srcFormXObject.get()->ref();
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001878 } else {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001879 sMaskGS.reset(SkPDFGraphicState::GetSMaskGraphicState(
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001880 srcFormXObject.get(),
1881 xfermode == SkXfermode::kDstOut_Mode,
1882 SkPDFGraphicState::kAlpha_SMaskMode));
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001883 // dst already added to fXObjectResources in drawFormXObjectWithClip.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001884 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001885 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001886 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001887
1888 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001889 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001890
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001891 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001892 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001893 &inClipContentEntry.entry()->fContent);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001894}
1895
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001896bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001897 ContentEntry* contentEntries = getContentEntries()->get();
1898 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1899 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001900 return true;
1901 }
1902 return false;
1903}
1904
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001905void SkPDFDevice::populateGraphicStateEntryFromPaint(
1906 const SkMatrix& matrix,
1907 const SkClipStack& clipStack,
1908 const SkRegion& clipRegion,
1909 const SkPaint& paint,
1910 bool hasText,
1911 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001912 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001913
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001914 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1915 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001916
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001917 entry->fMatrix = matrix;
1918 entry->fClipStack = clipStack;
1919 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001920 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1921 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001922
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001923 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001924 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001925 const SkShader* shader = paint.getShader();
1926 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001927 if (shader) {
1928 // PDF positions patterns relative to the initial transform, so
1929 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001930 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001931 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001932
1933 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001934 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001935 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001936
1937 // We need to apply the initial transform to bounds in order to get
1938 // bounds in a consistent coordinate system.
1939 SkRect boundsTemp;
1940 boundsTemp.set(bounds);
1941 fInitialTransform.mapRect(&boundsTemp);
1942 boundsTemp.roundOut(&bounds);
1943
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001944 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001945
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001946 if (pdfShader.get()) {
1947 // pdfShader has been canonicalized so we can directly compare
1948 // pointers.
1949 int resourceIndex = fShaderResources.find(pdfShader.get());
1950 if (resourceIndex < 0) {
1951 resourceIndex = fShaderResources.count();
1952 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001953 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001954 }
1955 entry->fShaderIndex = resourceIndex;
1956 } else {
1957 // A color shader is treated as an invalid shader so we don't have
1958 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001959 SkShader::GradientInfo gradientInfo;
1960 SkColor gradientColor;
1961 gradientInfo.fColors = &gradientColor;
1962 gradientInfo.fColorOffsets = NULL;
1963 gradientInfo.fColorCount = 1;
1964 if (shader->asAGradient(&gradientInfo) ==
1965 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001966 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1967 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001968 }
1969 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001970 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001971
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001972 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001973 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001974 newGraphicState.reset(
1975 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001976 } else {
1977 SkPaint newPaint = paint;
1978 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001979 newGraphicState.reset(
1980 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001981 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001982 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001983 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001984
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001985 if (hasText) {
1986 entry->fTextScaleX = paint.getTextScaleX();
1987 entry->fTextFill = paint.getStyle();
1988 } else {
1989 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001990 }
1991}
1992
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001993int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
1994 // Assumes that gs has been canonicalized (so we can directly compare
1995 // pointers).
1996 int result = fGraphicStateResources.find(gs);
1997 if (result < 0) {
1998 result = fGraphicStateResources.count();
1999 fGraphicStateResources.push(gs);
2000 gs->ref();
2001 }
2002 return result;
2003}
2004
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002005void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2006 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002007 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002008 if (contentEntry->fState.fFont == NULL ||
2009 contentEntry->fState.fTextSize != paint.getTextSize() ||
2010 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002011 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002012 contentEntry->fContent.writeText("/");
2013 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2014 SkPDFResourceDict::kFont_ResourceType,
2015 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002016 contentEntry->fContent.writeText(" ");
2017 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2018 contentEntry->fContent.writeText(" Tf\n");
2019 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002020 }
2021}
2022
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002023int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002024 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002025 int resourceIndex = fFontResources.find(newFont.get());
2026 if (resourceIndex < 0) {
2027 resourceIndex = fFontResources.count();
2028 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002029 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002030 }
2031 return resourceIndex;
2032}
2033
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002034void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002035 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002036 const SkRegion& origClipRegion,
2037 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002038 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002039 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002040 SkMatrix matrix = origMatrix;
2041 SkRegion perspectiveBounds;
2042 const SkRegion* clipRegion = &origClipRegion;
2043 SkBitmap perspectiveBitmap;
2044 const SkBitmap* bitmap = &origBitmap;
2045 SkBitmap tmpSubsetBitmap;
2046
2047 // Rasterize the bitmap using perspective in a new bitmap.
2048 if (origMatrix.hasPerspective()) {
2049 SkBitmap* subsetBitmap;
2050 if (srcRect) {
2051 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2052 return;
2053 }
2054 subsetBitmap = &tmpSubsetBitmap;
2055 } else {
2056 subsetBitmap = &tmpSubsetBitmap;
2057 *subsetBitmap = origBitmap;
2058 }
2059 srcRect = NULL;
2060
2061 // Transform the bitmap in the new space.
2062 SkPath perspectiveOutline;
2063 perspectiveOutline.addRect(
2064 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2065 SkIntToScalar(subsetBitmap->height())));
2066 perspectiveOutline.transform(origMatrix);
2067
2068 // TODO(edisonn): perf - use current clip too.
2069 // Retrieve the bounds of the new shape.
2070 SkRect bounds = perspectiveOutline.getBounds();
2071
2072 // TODO(edisonn): add DPI settings. Currently 1 pixel/point, which does
2073 // not look great, but it is not producing large PDFs.
2074
2075 // TODO(edisonn): A better approach would be to use a bitmap shader
2076 // (in clamp mode) and draw a rect over the entire bounding box. Then
2077 // intersect perspectiveOutline to the clip. That will avoid introducing
2078 // alpha to the image while still giving good behavior at the edge of
2079 // the image. Avoiding alpha will reduce the pdf size and generation
2080 // CPU time some.
2081
2082 perspectiveBitmap.setConfig(SkBitmap::kARGB_8888_Config,
2083 SkScalarCeilToInt(bounds.width()),
2084 SkScalarCeilToInt(bounds.height()));
2085 perspectiveBitmap.allocPixels();
2086 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2087
2088 SkBitmapDevice device(perspectiveBitmap);
2089 SkCanvas canvas(&device);
2090
2091 SkScalar deltaX = bounds.left();
2092 SkScalar deltaY = bounds.top();
2093
2094 SkMatrix offsetMatrix = origMatrix;
2095 offsetMatrix.postTranslate(-deltaX, -deltaY);
2096
2097 // Translate the draw in the new canvas, so we perfectly fit the
2098 // shape in the bitmap.
2099 canvas.setMatrix(offsetMatrix);
2100
2101 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2102
2103 // Make sure the final bits are in the bitmap.
2104 canvas.flush();
2105
2106 // In the new space, we use the identity matrix translated.
2107 matrix.setTranslate(deltaX, deltaY);
2108 perspectiveBounds.setRect(
2109 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2110 SkScalarFloorToInt(bounds.y()),
2111 SkScalarCeilToInt(bounds.width()),
2112 SkScalarCeilToInt(bounds.height())));
2113 clipRegion = &perspectiveBounds;
2114 srcRect = NULL;
2115 bitmap = &perspectiveBitmap;
2116 }
2117
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002118 SkMatrix scaled;
2119 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002120 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2121 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002122 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002123 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002124 scaled.postScale(SkIntToScalar(subset.width()),
2125 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002126 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002127 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002128 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002129 return;
2130 }
2131
2132 if (srcRect && !subset.intersect(*srcRect)) {
2133 return;
2134 }
2135
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002136 SkPDFImage* image = SkPDFImage::CreateImage(*bitmap, subset, fEncoder);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002137 if (!image) {
2138 return;
2139 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002140
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002141 fXObjectResources.push(image); // Transfer reference.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002142 SkPDFUtils::DrawFormXObject(fXObjectResources.count() - 1,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002143 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002144}
reed@google.com982cb872011-12-07 18:34:08 +00002145
2146bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2147 SkCanvas::Config8888) {
2148 return false;
2149}
reed@google.comb55deeb2012-01-06 14:43:09 +00002150
2151bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2152 return false;
2153}