blob: de71253d92c9102b4573f12c2b310e9a8903f9a4 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000015#include "SkFontHost.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000016#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000018#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
23#include "SkPDFImage.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000024#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000026#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000029#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000030#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000031#include "SkString.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000032#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000033#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000034#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000035#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000036
djsollen@google.com5df5e612013-10-03 14:42:24 +000037#ifdef SK_BUILD_FOR_ANDROID
38#include "SkTypeface_android.h"
39
40struct TypefaceFallbackData {
41 SkTypeface* typeface;
42 int lowerBounds;
43 int upperBounds;
44
45 bool operator==(const TypefaceFallbackData& b) const {
46 return typeface == b.typeface &&
47 lowerBounds == b.lowerBounds &&
48 upperBounds == b.upperBounds;
49 }
50};
51#endif
52
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000053// Utility functions
54
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000055static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000056 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
57 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000058 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000059 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
60 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000061 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000062 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
63 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000064 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000065 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
66 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000067}
68
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000069static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000070 SkPaint result = paint;
71 if (result.isFakeBoldText()) {
72 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
73 kStdFakeBoldInterpKeys,
74 kStdFakeBoldInterpValues,
75 kStdFakeBoldInterpLength);
76 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000077 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000078 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000079 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000081 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000082 result.setStrokeWidth(width);
83 }
84 return result;
85}
86
87// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000088static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000089 const uint16_t* glyphs, size_t len,
90 SkScalar* x, SkScalar* y) {
91 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000092 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000093 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000094
95 SkMatrix ident;
96 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000097 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000098 SkGlyphCache* cache = autoCache.getCache();
99
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000100 const char* start = reinterpret_cast<const char*>(glyphs);
101 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000102 SkFixed xAdv = 0, yAdv = 0;
103
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000104 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000105 while (start < stop) {
106 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
107 xAdv += glyph.fAdvanceX;
108 yAdv += glyph.fAdvanceY;
109 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000110 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000111 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000112 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000113
114 SkScalar xAdj = SkFixedToScalar(xAdv);
115 SkScalar yAdj = SkFixedToScalar(yAdv);
116 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
117 xAdj = SkScalarHalf(xAdj);
118 yAdj = SkScalarHalf(yAdj);
119 }
120 *x = *x - xAdj;
121 *y = *y - yAdj;
122}
123
reed@google.comfed86bd2013-03-14 15:04:57 +0000124static size_t max_glyphid_for_typeface(SkTypeface* typeface) {
125 SkAutoResolveDefaultTypeface autoResolve(typeface);
126 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000127 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000128}
129
130typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
131
132static size_t force_glyph_encoding(const SkPaint& paint, const void* text,
133 size_t len, SkGlyphStorage* storage,
134 uint16_t** glyphIDs) {
135 // Make sure we have a glyph id encoding.
136 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
137 size_t numGlyphs = paint.textToGlyphs(text, len, NULL);
138 storage->reset(numGlyphs);
139 paint.textToGlyphs(text, len, storage->get());
140 *glyphIDs = storage->get();
141 return numGlyphs;
142 }
143
144 // For user supplied glyph ids we need to validate them.
145 SkASSERT((len & 1) == 0);
146 size_t numGlyphs = len / 2;
147 const uint16_t* input =
148 reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
149
150 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
151 size_t validated;
152 for (validated = 0; validated < numGlyphs; ++validated) {
153 if (input[validated] > maxGlyphID) {
154 break;
155 }
156 }
157 if (validated >= numGlyphs) {
158 *glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
159 return numGlyphs;
160 }
161
162 // Silently drop anything out of range.
163 storage->reset(numGlyphs);
164 if (validated > 0) {
165 memcpy(storage->get(), input, validated * sizeof(uint16_t));
166 }
167
168 for (size_t i = validated; i < numGlyphs; ++i) {
169 storage->get()[i] = input[i];
170 if (input[i] > maxGlyphID) {
171 storage->get()[i] = 0;
172 }
173 }
174 *glyphIDs = storage->get();
175 return numGlyphs;
176}
177
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000178static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
179 SkWStream* content) {
180 // Flip the text about the x-axis to account for origin swap and include
181 // the passed parameters.
182 content->writeText("1 0 ");
183 SkPDFScalar::Append(0 - textSkewX, content);
184 content->writeText(" -1 ");
185 SkPDFScalar::Append(x, content);
186 content->writeText(" ");
187 SkPDFScalar::Append(y, content);
188 content->writeText(" Tm\n");
189}
190
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000191// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
192// later being our representation of an object in the PDF file.
193struct GraphicStateEntry {
194 GraphicStateEntry();
195
196 // Compare the fields we care about when setting up a new content entry.
197 bool compareInitialState(const GraphicStateEntry& b);
198
199 SkMatrix fMatrix;
200 // We can't do set operations on Paths, though PDF natively supports
201 // intersect. If the clip stack does anything other than intersect,
202 // we have to fall back to the region. Treat fClipStack as authoritative.
203 // See http://code.google.com/p/skia/issues/detail?id=221
204 SkClipStack fClipStack;
205 SkRegion fClipRegion;
206
207 // When emitting the content entry, we will ensure the graphic state
208 // is set to these values first.
209 SkColor fColor;
210 SkScalar fTextScaleX; // Zero means we don't care what the value is.
211 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
212 int fShaderIndex;
213 int fGraphicStateIndex;
214
215 // We may change the font (i.e. for Type1 support) within a
216 // ContentEntry. This is the one currently in effect, or NULL if none.
217 SkPDFFont* fFont;
218 // In PDF, text size has no default value. It is only valid if fFont is
219 // not NULL.
220 SkScalar fTextSize;
221};
222
223GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
224 fTextScaleX(SK_Scalar1),
225 fTextFill(SkPaint::kFill_Style),
226 fShaderIndex(-1),
227 fGraphicStateIndex(-1),
228 fFont(NULL),
229 fTextSize(SK_ScalarNaN) {
230 fMatrix.reset();
231}
232
233bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& b) {
234 return fColor == b.fColor &&
235 fShaderIndex == b.fShaderIndex &&
236 fGraphicStateIndex == b.fGraphicStateIndex &&
237 fMatrix == b.fMatrix &&
238 fClipStack == b.fClipStack &&
239 (fTextScaleX == 0 ||
240 b.fTextScaleX == 0 ||
241 (fTextScaleX == b.fTextScaleX && fTextFill == b.fTextFill));
242}
243
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000244class GraphicStackState {
245public:
246 GraphicStackState(const SkClipStack& existingClipStack,
247 const SkRegion& existingClipRegion,
248 SkWStream* contentStream)
249 : fStackDepth(0),
250 fContentStream(contentStream) {
251 fEntries[0].fClipStack = existingClipStack;
252 fEntries[0].fClipRegion = existingClipRegion;
253 }
254
255 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000256 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000257 void updateMatrix(const SkMatrix& matrix);
258 void updateDrawingState(const GraphicStateEntry& state);
259
260 void drainStack();
261
262private:
263 void push();
264 void pop();
265 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
266
267 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
268 static const int kMaxStackDepth = 12;
269 GraphicStateEntry fEntries[kMaxStackDepth + 1];
270 int fStackDepth;
271 SkWStream* fContentStream;
272};
273
274void GraphicStackState::drainStack() {
275 while (fStackDepth) {
276 pop();
277 }
278}
279
280void GraphicStackState::push() {
281 SkASSERT(fStackDepth < kMaxStackDepth);
282 fContentStream->writeText("q\n");
283 fStackDepth++;
284 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
285}
286
287void GraphicStackState::pop() {
288 SkASSERT(fStackDepth > 0);
289 fContentStream->writeText("Q\n");
290 fStackDepth--;
291}
292
robertphillips@google.com80214e22012-07-20 15:33:18 +0000293// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000294// and then skips over the leading entries as specified in prefix. It requires
295// and asserts that "prefix" will be a prefix to "stack."
296static void skip_clip_stack_prefix(const SkClipStack& prefix,
297 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000298 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000299 SkClipStack::B2TIter prefixIter(prefix);
300 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000301
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000302 const SkClipStack::Element* prefixEntry;
303 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000304
305 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000306 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000307 iterEntry = iter->next();
308 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000309 // Because of SkClipStack does internal intersection, the last clip
310 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000311 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000312 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
313 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
314 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000315 // back up the iterator by one
316 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000317 prefixEntry = prefixIter.next();
318 break;
319 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000320 }
321
322 SkASSERT(prefixEntry == NULL);
323}
324
325static void emit_clip(SkPath* clipPath, SkRect* clipRect,
326 SkWStream* contentStream) {
327 SkASSERT(clipPath || clipRect);
328
329 SkPath::FillType clipFill;
330 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000331 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000332 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000333 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000334 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
335 clipFill = SkPath::kWinding_FillType;
336 }
337
338 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
339 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
340 if (clipFill == SkPath::kEvenOdd_FillType) {
341 contentStream->writeText("W* n\n");
342 } else {
343 contentStream->writeText("W n\n");
344 }
345}
346
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000347#ifdef SK_PDF_USE_PATHOPS
348/* Calculate an inverted path's equivalent non-inverted path, given the
349 * canvas bounds.
350 * outPath may alias with invPath (since this is supported by PathOps).
351 */
352static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
353 SkPath* outPath) {
354 SkASSERT(invPath.isInverseFillType());
355
356 SkPath clipPath;
357 clipPath.addRect(bounds);
358
359 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
360}
361
362// Sanity check the numerical values of the SkRegion ops and PathOps ops
363// enums so region_op_to_pathops_op can do a straight passthrough cast.
364// If these are failing, it may be necessary to make region_op_to_pathops_op
365// do more.
366SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
367 region_pathop_mismatch);
368SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
369 region_pathop_mismatch);
370SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
371 region_pathop_mismatch);
372SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
373 region_pathop_mismatch);
374SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
375 (int)kReverseDifference_PathOp,
376 region_pathop_mismatch);
377
378static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
379 SkASSERT(op >= 0);
380 SkASSERT(op <= SkRegion::kReverseDifference_Op);
381 return (SkPathOp)op;
382}
383
384/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
385 * Returns true if successful, or false if not successful.
386 * If successful, the resulting clip is stored in outClipPath.
387 * If not successful, outClipPath is undefined, and a fallback method
388 * should be used.
389 */
390static bool get_clip_stack_path(const SkMatrix& transform,
391 const SkClipStack& clipStack,
392 const SkRegion& clipRegion,
393 SkPath* outClipPath) {
394 outClipPath->reset();
395 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
396
397 const SkClipStack::Element* clipEntry;
398 SkClipStack::Iter iter;
399 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
400 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
401 SkPath entryPath;
402 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
403 outClipPath->reset();
404 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
405 continue;
406 } else if (SkClipStack::Element::kRect_Type == clipEntry->getType()) {
407 entryPath.addRect(clipEntry->getRect());
408 } else if (SkClipStack::Element::kPath_Type == clipEntry->getType()) {
409 entryPath = clipEntry->getPath();
410 }
411 entryPath.transform(transform);
412
413 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
414 *outClipPath = entryPath;
415 } else {
416 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
417 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
418 return false;
419 }
420 }
421 }
422
423 if (outClipPath->isInverseFillType()) {
424 // The bounds are slightly outset to ensure this is correct in the
425 // face of floating-point accuracy and possible SkRegion bitmap
426 // approximations.
427 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
428 clipBounds.outset(SK_Scalar1, SK_Scalar1);
429 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
430 return false;
431 }
432 }
433 return true;
434}
435#endif
436
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000437// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000438// graphic state stack, and the fact that we can know all the clips used
439// on the page to optimize this.
440void GraphicStackState::updateClip(const SkClipStack& clipStack,
441 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000442 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000443 if (clipStack == currentEntry()->fClipStack) {
444 return;
445 }
446
447 while (fStackDepth > 0) {
448 pop();
449 if (clipStack == currentEntry()->fClipStack) {
450 return;
451 }
452 }
453 push();
454
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000455 currentEntry()->fClipStack = clipStack;
456 currentEntry()->fClipRegion = clipRegion;
457
458 SkMatrix transform;
459 transform.setTranslate(translation.fX, translation.fY);
460
461#ifdef SK_PDF_USE_PATHOPS
462 SkPath clipPath;
463 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
464 emit_clip(&clipPath, NULL, fContentStream);
465 return;
466 }
467#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000468 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
469 // already been applied. (If this is a top level device, then it specifies
470 // a clip to the content area. If this is a layer, then it specifies
471 // the clip in effect when the layer was created.) There's no need to
472 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
473 // initial clip on the parent layer. (This means there's a bug if the user
474 // expands the clip and then uses any xfer mode that uses dst:
475 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000476 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000477 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
478
479 // If the clip stack does anything other than intersect or if it uses
480 // an inverse fill type, we have to fall back to the clip region.
481 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000482 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000483 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000484 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
485 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000486 needRegion = true;
487 break;
488 }
489 }
490
491 if (needRegion) {
492 SkPath clipPath;
493 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
494 emit_clip(&clipPath, NULL, fContentStream);
495 } else {
496 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000497 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000498 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000499 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
500 switch (clipEntry->getType()) {
501 case SkClipStack::Element::kRect_Type: {
502 SkRect translatedClip;
503 transform.mapRect(&translatedClip, clipEntry->getRect());
504 emit_clip(NULL, &translatedClip, fContentStream);
505 break;
506 }
507 case SkClipStack::Element::kPath_Type: {
508 SkPath translatedPath;
509 clipEntry->getPath().transform(transform, &translatedPath);
510 emit_clip(&translatedPath, NULL, fContentStream);
511 break;
512 }
513 default:
514 SkASSERT(false);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000515 }
516 }
517 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000518}
519
520void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
521 if (matrix == currentEntry()->fMatrix) {
522 return;
523 }
524
525 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
526 SkASSERT(fStackDepth > 0);
527 SkASSERT(fEntries[fStackDepth].fClipStack ==
528 fEntries[fStackDepth -1].fClipStack);
529 pop();
530
531 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
532 }
533 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
534 return;
535 }
536
537 push();
538 SkPDFUtils::AppendTransform(matrix, fContentStream);
539 currentEntry()->fMatrix = matrix;
540}
541
542void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
543 // PDF treats a shader as a color, so we only set one or the other.
544 if (state.fShaderIndex >= 0) {
545 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000546 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000547 currentEntry()->fShaderIndex = state.fShaderIndex;
548 }
549 } else {
550 if (state.fColor != currentEntry()->fColor ||
551 currentEntry()->fShaderIndex >= 0) {
552 emit_pdf_color(state.fColor, fContentStream);
553 fContentStream->writeText("RG ");
554 emit_pdf_color(state.fColor, fContentStream);
555 fContentStream->writeText("rg\n");
556 currentEntry()->fColor = state.fColor;
557 currentEntry()->fShaderIndex = -1;
558 }
559 }
560
561 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000562 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000563 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
564 }
565
566 if (state.fTextScaleX) {
567 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
568 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
569 SkIntToScalar(100));
570 SkPDFScalar::Append(pdfScale, fContentStream);
571 fContentStream->writeText(" Tz\n");
572 currentEntry()->fTextScaleX = state.fTextScaleX;
573 }
574 if (state.fTextFill != currentEntry()->fTextFill) {
575 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
576 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
577 enum_must_match_value);
578 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
579 enum_must_match_value);
580 fContentStream->writeDecAsText(state.fTextFill);
581 fContentStream->writeText(" Tr\n");
582 currentEntry()->fTextFill = state.fTextFill;
583 }
584 }
585}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000586
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000587SkBaseDevice* SkPDFDevice::onCreateCompatibleDevice(SkBitmap::Config config,
588 int width, int height,
589 bool isOpaque,
590 Usage usage) {
bsalomon@google.come97f0852011-06-17 13:10:25 +0000591 SkMatrix initialTransform;
592 initialTransform.reset();
593 SkISize size = SkISize::Make(width, height);
594 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
595}
596
597
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000598struct ContentEntry {
599 GraphicStateEntry fState;
600 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000601 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000602
603 // If the stack is too deep we could get Stack Overflow.
604 // So we manually destruct the object.
605 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000606 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000607 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000608 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000609 // When the destructor is called, fNext is NULL and exits.
610 delete val;
611 val = valNext;
612 }
613 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000614};
615
616// A helper class to automatically finish a ContentEntry at the end of a
617// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000618class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000619public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000620 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
621 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000622 : fDevice(device),
623 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000624 fXfermode(SkXfermode::kSrcOver_Mode),
625 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000626 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
627 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000628 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
629 const SkRegion& clipRegion, const SkMatrix& matrix,
630 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000631 : fDevice(device),
632 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000633 fXfermode(SkXfermode::kSrcOver_Mode),
634 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000635 init(clipStack, clipRegion, matrix, paint, hasText);
636 }
637
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000638 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000639 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000640 SkPath* shape = &fShape;
641 if (shape->isEmpty()) {
642 shape = NULL;
643 }
644 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000645 }
reed@google.comfc641d02012-09-20 17:52:20 +0000646 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000647 }
648
649 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000650
651 /* Returns true when we explicitly need the shape of the drawing. */
652 bool needShape() {
653 switch (fXfermode) {
654 case SkXfermode::kClear_Mode:
655 case SkXfermode::kSrc_Mode:
656 case SkXfermode::kSrcIn_Mode:
657 case SkXfermode::kSrcOut_Mode:
658 case SkXfermode::kDstIn_Mode:
659 case SkXfermode::kDstOut_Mode:
660 case SkXfermode::kSrcATop_Mode:
661 case SkXfermode::kDstATop_Mode:
662 case SkXfermode::kModulate_Mode:
663 return true;
664 default:
665 return false;
666 }
667 }
668
669 /* Returns true unless we only need the shape of the drawing. */
670 bool needSource() {
671 if (fXfermode == SkXfermode::kClear_Mode) {
672 return false;
673 }
674 return true;
675 }
676
677 /* If the shape is different than the alpha component of the content, then
678 * setShape should be called with the shape. In particular, images and
679 * devices have rectangular shape.
680 */
681 void setShape(const SkPath& shape) {
682 fShape = shape;
683 }
684
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000685private:
686 SkPDFDevice* fDevice;
687 ContentEntry* fContentEntry;
688 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000689 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000690 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000691
692 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
693 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000694 // Shape has to be flatten before we get here.
695 if (matrix.hasPerspective()) {
696 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000697 return;
698 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000699 if (paint.getXfermode()) {
700 paint.getXfermode()->asMode(&fXfermode);
701 }
702 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
703 matrix, paint, hasText,
704 &fDstFormXObject);
705 }
706};
707
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000708////////////////////////////////////////////////////////////////////////////////
709
ctguil@chromium.org15261292011-04-29 17:54:16 +0000710static inline SkBitmap makeContentBitmap(const SkISize& contentSize,
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000711 const SkMatrix* initialTransform) {
reed@android.comf2b98d62010-12-20 18:26:13 +0000712 SkBitmap bitmap;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000713 if (initialTransform) {
714 // Compute the size of the drawing area.
715 SkVector drawingSize;
716 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000717 drawingSize.set(SkIntToScalar(contentSize.fWidth),
718 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000719 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000720 // This shouldn't happen, initial transform should be invertible.
721 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000722 inverse.reset();
723 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000724 inverse.mapVectors(&drawingSize, 1);
725 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
726 bitmap.setConfig(SkBitmap::kNo_Config, abs(size.fWidth),
727 abs(size.fHeight));
728 } else {
729 bitmap.setConfig(SkBitmap::kNo_Config, abs(contentSize.fWidth),
730 abs(contentSize.fHeight));
731 }
732
reed@android.comf2b98d62010-12-20 18:26:13 +0000733 return bitmap;
734}
735
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000736// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000737SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000738 const SkMatrix& initialTransform)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000739 : SkBitmapDevice(makeContentBitmap(contentSize, &initialTransform)),
ctguil@chromium.org15261292011-04-29 17:54:16 +0000740 fPageSize(pageSize),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000741 fContentSize(contentSize),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000742 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000743 fLastMarginContentEntry(NULL),
edisonn@google.comd9dfa182013-04-24 13:01:01 +0000744 fClipStack(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000745 fEncoder(NULL),
746 fRasterDpi(SkFloatToScalar(72.0f)) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000747 // Just report that PDF does not supports perspective in the
748 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000749 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
750
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000751 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000752 // origin at the bottom left. This matrix corrects for that. But that only
753 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000754 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
755 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000756 fInitialTransform.preConcat(initialTransform);
757
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000758 SkIRect existingClip = SkIRect::MakeWH(this->width(), this->height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000759 fExistingClipRegion.setRect(existingClip);
760
761 this->init();
762}
763
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000764// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000765SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
766 const SkClipStack& existingClipStack,
767 const SkRegion& existingClipRegion)
robertphillips@google.com1f2f3382013-08-29 11:54:56 +0000768 : SkBitmapDevice(makeContentBitmap(layerSize, NULL)),
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000769 fPageSize(layerSize),
770 fContentSize(layerSize),
771 fExistingClipStack(existingClipStack),
772 fExistingClipRegion(existingClipRegion),
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000773 fLastContentEntry(NULL),
robertphillips@google.com40a1ae42012-07-13 15:36:15 +0000774 fLastMarginContentEntry(NULL),
commit-bot@chromium.org8c294902013-10-21 17:14:37 +0000775 fClipStack(NULL),
776 fEncoder(NULL),
777 fRasterDpi(SkFloatToScalar(72.0f)) {
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000778 fInitialTransform.reset();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000779 this->init();
780}
781
782SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000783 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000784}
785
786void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000787 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000788 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000789 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000790 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000791 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000792 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000793 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000794 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000795 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
796 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000797}
798
vandebo@chromium.org98594282011-07-25 22:34:12 +0000799void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000800 fGraphicStateResources.unrefAll();
801 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000802 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000803 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000804 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000805 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000806 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000807
vandebo@chromium.org98594282011-07-25 22:34:12 +0000808 if (clearFontUsage) {
809 fFontGlyphUsage->reset();
810 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000811}
812
reed@google.com982cb872011-12-07 18:34:08 +0000813uint32_t SkPDFDevice::getDeviceCapabilities() {
814 return kVector_Capability;
815}
816
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000817void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000818 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000819 this->init();
820
821 SkPaint paint;
822 paint.setColor(color);
823 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000824 SkMatrix identity;
825 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000826 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
827 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000828 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000829}
830
831void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000832 SkPaint newPaint = paint;
833 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000834 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000835 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000836}
837
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000838void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
839 ContentEntry* contentEntry) {
840 if (!contentEntry) {
841 return;
842 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000843 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
844 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000845 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000846 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000847 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000848 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000849 inverse.mapRect(&bbox);
850
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000851 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000852 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000853 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000854}
855
856void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
857 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000858 const SkPaint& passedPaint) {
859 if (count == 0) {
860 return;
861 }
862
epoger@google.comb58772f2013-03-08 09:09:10 +0000863 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
864 return;
865 }
866
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000867 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
868 // We only use this when there's a path effect because of the overhead
869 // of multiple calls to setUpContentEntry it causes.
870 if (passedPaint.getPathEffect()) {
871 if (d.fClip->isEmpty()) {
872 return;
873 }
874 SkDraw pointDraw(d);
875 pointDraw.fDevice = this;
876 pointDraw.drawPoints(mode, count, points, passedPaint, true);
877 return;
878 }
879
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000880 const SkPaint* paint = &passedPaint;
881 SkPaint modifiedPaint;
882
883 if (mode == SkCanvas::kPoints_PointMode &&
884 paint->getStrokeCap() != SkPaint::kRound_Cap) {
885 modifiedPaint = *paint;
886 paint = &modifiedPaint;
887 if (paint->getStrokeWidth()) {
888 // PDF won't draw a single point with square/butt caps because the
889 // orientation is ambiguous. Draw a rectangle instead.
890 modifiedPaint.setStyle(SkPaint::kFill_Style);
891 SkScalar strokeWidth = paint->getStrokeWidth();
892 SkScalar halfStroke = SkScalarHalf(strokeWidth);
893 for (size_t i = 0; i < count; i++) {
894 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
895 r.inset(-halfStroke, -halfStroke);
896 drawRect(d, r, modifiedPaint);
897 }
898 return;
899 } else {
900 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
901 }
902 }
903
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000904 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000905 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000906 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000907 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000908
909 switch (mode) {
910 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000911 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000912 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000913 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000914 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000915 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000916 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000917 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000918 break;
919 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000920 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000921 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000922 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000923 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000924 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000925 &content.entry()->fContent);
926 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000927 }
928 break;
929 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000930 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
931 for (size_t i = 0; i < count; i++) {
932 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000933 &content.entry()->fContent);
934 SkPDFUtils::ClosePath(&content.entry()->fContent);
935 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000936 }
937 break;
938 default:
939 SkASSERT(false);
940 }
941}
942
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000943void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000944 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000945 SkRect r = rect;
946 r.sort();
947
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000948 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000949 if (d.fClip->isEmpty()) {
950 return;
951 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000952 SkPath path;
953 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000954 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000955 return;
956 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000957
epoger@google.comb58772f2013-03-08 09:09:10 +0000958 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000959 return;
960 }
961
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000962 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000963 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000964 return;
965 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000966 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000967 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000968 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000969}
970
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000971void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect,
972 const SkPaint& paint) {
973 SkPath path;
974 path.addRRect(rrect);
975 this->drawPath(draw, path, paint, NULL, true);
976}
977
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000978void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000979 const SkPaint& paint, const SkMatrix* prePathMatrix,
980 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000981 SkPath modifiedPath;
982 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
983
984 SkMatrix matrix = *d.fMatrix;
985 if (prePathMatrix) {
986 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
987 if (!pathIsMutable) {
988 pathPtr = &modifiedPath;
989 pathIsMutable = true;
990 }
991 origPath.transform(*prePathMatrix, pathPtr);
992 } else {
993 if (!matrix.preConcat(*prePathMatrix)) {
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000994 // TODO(edisonn): report somehow why we failed?
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000995 return;
996 }
997 }
998 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000999
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001000 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001001 if (d.fClip->isEmpty()) {
1002 return;
1003 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001004 if (!pathIsMutable) {
1005 pathPtr = &modifiedPath;
1006 pathIsMutable = true;
1007 }
1008 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001009
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001010 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001011 noEffectPaint.setPathEffect(NULL);
1012 if (fill) {
1013 noEffectPaint.setStyle(SkPaint::kFill_Style);
1014 } else {
1015 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1016 noEffectPaint.setStrokeWidth(0);
1017 }
1018 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001019 return;
1020 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001021
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001022#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001023 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001024 return;
1025 }
1026#endif
1027
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001028 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001029 return;
1030 }
1031
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001032 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001033 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001034 return;
1035 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001036 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1037 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001038 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001039 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001040}
1041
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001042void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1043 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001044 const SkPaint& paint,
1045 SkCanvas::DrawBitmapRectFlags flags) {
1046 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001047 SkMatrix matrix;
1048 SkRect bitmapBounds, tmpSrc, tmpDst;
1049 SkBitmap tmpBitmap;
1050
1051 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1052
1053 // Compute matrix from the two rectangles
1054 if (src) {
1055 tmpSrc = *src;
1056 } else {
1057 tmpSrc = bitmapBounds;
1058 }
1059 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1060
1061 const SkBitmap* bitmapPtr = &bitmap;
1062
1063 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1064 // needed (if the src was clipped). No check needed if src==null.
1065 if (src) {
1066 if (!bitmapBounds.contains(*src)) {
1067 if (!tmpSrc.intersect(bitmapBounds)) {
1068 return; // nothing to draw
1069 }
1070 // recompute dst, based on the smaller tmpSrc
1071 matrix.mapRect(&tmpDst, tmpSrc);
1072 }
1073
1074 // since we may need to clamp to the borders of the src rect within
1075 // the bitmap, we extract a subset.
1076 // TODO: make sure this is handled in drawBitmap and remove from here.
1077 SkIRect srcIR;
1078 tmpSrc.roundOut(&srcIR);
1079 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1080 return;
1081 }
1082 bitmapPtr = &tmpBitmap;
1083
1084 // Since we did an extract, we need to adjust the matrix accordingly
1085 SkScalar dx = 0, dy = 0;
1086 if (srcIR.fLeft > 0) {
1087 dx = SkIntToScalar(srcIR.fLeft);
1088 }
1089 if (srcIR.fTop > 0) {
1090 dy = SkIntToScalar(srcIR.fTop);
1091 }
1092 if (dx || dy) {
1093 matrix.preTranslate(dx, dy);
1094 }
1095 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001096 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001097}
1098
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001099void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001100 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001101 if (d.fClip->isEmpty()) {
1102 return;
1103 }
1104
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001105 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001106 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001107 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1108 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001109}
1110
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001111void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001112 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001113 if (d.fClip->isEmpty()) {
1114 return;
1115 }
1116
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001117 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001118 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001119 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1120 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001121}
1122
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001123void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001124 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001125 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1126 if (paint.getMaskFilter() != NULL) {
1127 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1128 // making text unreadable (e.g. same text twice when using CSS shadows).
1129 return;
1130 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +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.orgfb0b0ed2011-04-15 20:01:17 +00001134 return;
1135 }
1136
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001137 SkGlyphStorage storage(0);
1138 uint16_t* glyphIDs = NULL;
1139 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1140 &glyphIDs);
1141 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001142
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001143 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001144 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001145 content.entry()->fContent.writeText("BT\n");
1146 set_text_transform(x, y, textPaint.getTextSkewX(),
1147 &content.entry()->fContent);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001148 size_t consumedGlyphCount = 0;
1149 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001150 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1151 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001152 size_t availableGlyphs =
1153 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1154 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001155 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1156 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001157 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001158 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001159 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001160 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001161 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001162 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001163 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001164 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001165}
1166
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001167void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001168 const SkScalar pos[], SkScalar constY,
1169 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001170 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1171 if (paint.getMaskFilter() != NULL) {
1172 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1173 // making text unreadable (e.g. same text twice when using CSS shadows).
1174 return;
1175 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001176 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001177 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001178 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001179 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001180 return;
1181 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001182
djsollen@google.com5df5e612013-10-03 14:42:24 +00001183#ifdef SK_BUILD_FOR_ANDROID
1184 /*
1185 * In the case that we have enabled fallback fonts on Android we need to
1186 * take the following steps to ensure that the PDF draws all characters,
1187 * regardless of their underlying font file, correctly.
1188 *
1189 * 1. Convert input into GlyphID encoding if it currently is not
1190 * 2. Iterate over the glyphIDs and identify the actual typeface that each
1191 * glyph resolves to
1192 * 3. Iterate over those typefaces and recursively call this function with
1193 * only the glyphs (and their positions) that the typeface is capable of
1194 * resolving.
1195 */
1196 if (paint.getPaintOptionsAndroid().isUsingFontFallbacks()) {
1197 uint16_t* glyphIDs = NULL;
1198 SkGlyphStorage tmpStorage(0);
1199 size_t numGlyphs = 0;
1200
1201 // convert to glyphIDs
1202 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1203 numGlyphs = len / 2;
1204 glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>(text));
1205 } else {
1206 numGlyphs = paint.textToGlyphs(text, len, NULL);
1207 tmpStorage.reset(numGlyphs);
1208 paint.textToGlyphs(text, len, tmpStorage.get());
1209 glyphIDs = tmpStorage.get();
1210 }
1211
1212 // if no typeface is provided in the paint get the default
1213 SkAutoTUnref<SkTypeface> origFace(SkSafeRef(paint.getTypeface()));
1214 if (NULL == origFace.get()) {
1215 origFace.reset(SkTypeface::RefDefault());
1216 }
1217 const uint16_t origGlyphCount = origFace->countGlyphs();
1218
1219 // keep a list of the already visited typefaces and some data about them
1220 SkTDArray<TypefaceFallbackData> visitedTypefaces;
1221
1222 // find all the typefaces needed to resolve this run of text
1223 bool usesOriginalTypeface = false;
1224 for (uint16_t x = 0; x < numGlyphs; ++x) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001225 // optimization that checks to see if original typeface can resolve
1226 // the glyph
djsollen@google.com5df5e612013-10-03 14:42:24 +00001227 if (glyphIDs[x] < origGlyphCount) {
1228 usesOriginalTypeface = true;
1229 continue;
1230 }
1231
1232 // find the fallback typeface that supports this glyph
1233 TypefaceFallbackData data;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001234 data.typeface =
1235 SkGetTypefaceForGlyphID(glyphIDs[x], origFace.get(),
1236 paint.getPaintOptionsAndroid(),
1237 &data.lowerBounds,
1238 &data.upperBounds);
djsollen@google.com5df5e612013-10-03 14:42:24 +00001239 // add the typeface and its data if we don't have it
1240 if (data.typeface && !visitedTypefaces.contains(data)) {
1241 visitedTypefaces.push(data);
1242 }
1243 }
1244
1245 // if the original font was used then add it to the list as well
1246 if (usesOriginalTypeface) {
1247 TypefaceFallbackData* data = visitedTypefaces.push();
1248 data->typeface = origFace.get();
1249 data->lowerBounds = 0;
1250 data->upperBounds = origGlyphCount;
1251 }
1252
1253 // keep a scratch glyph and pos storage
1254 SkAutoTMalloc<SkScalar> posStorage(len * scalarsPerPos);
1255 SkScalar* tmpPos = posStorage.get();
1256 SkGlyphStorage glyphStorage(numGlyphs);
1257 uint16_t* tmpGlyphIDs = glyphStorage.get();
1258
1259 // loop through all the valid typefaces, trim the glyphs to only those
1260 // resolved by the typeface, and then draw that run of glyphs
1261 for (int x = 0; x < visitedTypefaces.count(); ++x) {
1262 const TypefaceFallbackData& data = visitedTypefaces[x];
1263
1264 int tmpGlyphCount = 0;
1265 for (uint16_t y = 0; y < numGlyphs; ++y) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001266 if (glyphIDs[y] >= data.lowerBounds &&
1267 glyphIDs[y] < data.upperBounds) {
djsollen@google.com5df5e612013-10-03 14:42:24 +00001268 tmpGlyphIDs[tmpGlyphCount] = glyphIDs[y] - data.lowerBounds;
1269 memcpy(&(tmpPos[tmpGlyphCount * scalarsPerPos]),
1270 &(pos[y * scalarsPerPos]),
1271 scalarsPerPos * sizeof(SkScalar));
1272 tmpGlyphCount++;
1273 }
1274 }
1275
1276 // recursively call this function with the right typeface
1277 SkPaint tmpPaint = paint;
1278 tmpPaint.setTypeface(data.typeface);
1279 tmpPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1280
1281 // turn off fallback chaining
1282 SkPaintOptionsAndroid paintOpts = tmpPaint.getPaintOptionsAndroid();
1283 paintOpts.setUseFontFallbacks(false);
1284 tmpPaint.setPaintOptionsAndroid(paintOpts);
1285
1286 this->drawPosText(d, tmpGlyphIDs, tmpGlyphCount * 2, tmpPos, constY,
1287 scalarsPerPos, tmpPaint);
1288 }
1289 return;
1290 }
1291#endif
1292
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001293 SkGlyphStorage storage(0);
1294 uint16_t* glyphIDs = NULL;
1295 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1296 &glyphIDs);
1297 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001298
1299 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001300 content.entry()->fContent.writeText("BT\n");
1301 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001302 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001303 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001304 uint16_t encodedValue = glyphIDs[i];
1305 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001306 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001307 i--;
1308 continue;
1309 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001310 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001311 SkScalar x = pos[i * scalarsPerPos];
1312 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001313 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001314 set_text_transform(x, y, textPaint.getTextSkewX(),
1315 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001316 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001317 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001318 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001319 content.entry()->fContent.writeText(encodedString.c_str());
1320 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001321 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001322 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001323}
1324
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001325void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001326 const SkPath& path, const SkMatrix* matrix,
1327 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001328 if (d.fClip->isEmpty()) {
1329 return;
1330 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001331 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001332}
1333
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001334void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001335 int vertexCount, const SkPoint verts[],
1336 const SkPoint texs[], const SkColor colors[],
1337 SkXfermode* xmode, const uint16_t indices[],
1338 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001339 if (d.fClip->isEmpty()) {
1340 return;
1341 }
vandebo@chromium.orga5180862010-10-26 19:48:49 +00001342 NOT_IMPLEMENTED("drawVerticies", true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001343}
1344
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001345void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1346 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001347 if ((device->getDeviceCapabilities() & kVector_Capability) == 0) {
1348 // If we somehow get a raster device, do what our parent would do.
robertphillips@google.com1f2f3382013-08-29 11:54:56 +00001349 INHERITED::drawDevice(d, device, x, y, paint);
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001350 return;
1351 }
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +00001352
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001353 // Assume that a vector capable device means that it's a PDF Device.
1354 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001355 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001356 return;
1357 }
1358
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001359 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001360 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001361 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001362 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001363 return;
1364 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001365 if (content.needShape()) {
1366 SkPath shape;
1367 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001368 SkIntToScalar(device->width()),
1369 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001370 content.setShape(shape);
1371 }
1372 if (!content.needSource()) {
1373 return;
1374 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001375
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001376 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1377 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001378 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001379
1380 // Merge glyph sets from the drawn device.
1381 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001382}
1383
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001384void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1385 INHERITED::onAttachToCanvas(canvas);
1386
1387 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1388 fClipStack = canvas->getClipStack();
1389}
1390
1391void SkPDFDevice::onDetachFromCanvas() {
1392 INHERITED::onDetachFromCanvas();
1393
1394 fClipStack = NULL;
1395}
1396
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001397ContentEntry* SkPDFDevice::getLastContentEntry() {
1398 if (fDrawingArea == kContent_DrawingArea) {
1399 return fLastContentEntry;
1400 } else {
1401 return fLastMarginContentEntry;
1402 }
1403}
1404
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001405SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001406 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001407 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001408 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001409 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001410 }
1411}
1412
1413void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1414 if (fDrawingArea == kContent_DrawingArea) {
1415 fLastContentEntry = contentEntry;
1416 } else {
1417 fLastMarginContentEntry = contentEntry;
1418 }
1419}
1420
1421void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001422 // A ScopedContentEntry only exists during the course of a draw call, so
1423 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001424 fDrawingArea = drawingArea;
1425}
1426
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001427SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001428 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001429 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001430
1431 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001432 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001433 fResourceDict->insertResourceAsReference(
1434 SkPDFResourceDict::kExtGState_ResourceType,
1435 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001436 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001437 }
1438
1439 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001440 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001441 fResourceDict->insertResourceAsReference(
1442 SkPDFResourceDict::kXObject_ResourceType,
1443 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001444 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001445 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001446
1447 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001448 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001449 fResourceDict->insertResourceAsReference(
1450 SkPDFResourceDict::kFont_ResourceType,
1451 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001452 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001453 }
1454
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001455 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001456 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001457 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001458 fResourceDict->insertResourceAsReference(
1459 SkPDFResourceDict::kPattern_ResourceType,
1460 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001461 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001462 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001463 }
1464 return fResourceDict;
1465}
1466
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001467const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1468 return fFontResources;
1469}
1470
reed@google.com2a006c12012-09-19 17:05:55 +00001471SkPDFArray* SkPDFDevice::copyMediaBox() const {
1472 // should this be a singleton?
1473 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001474
reed@google.com2a006c12012-09-19 17:05:55 +00001475 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001476 mediaBox->reserve(4);
1477 mediaBox->append(zero.get());
1478 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001479 mediaBox->appendInt(fPageSize.fWidth);
1480 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001481 return mediaBox;
1482}
1483
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001484SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001485 SkMemoryStream* result = new SkMemoryStream;
1486 result->setData(this->copyContentToData())->unref();
1487 return result;
1488}
1489
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001490void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1491 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001492 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1493 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001494 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001495 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001496 SkPoint translation;
1497 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001498 translation.negate();
1499 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1500 translation);
1501 gsState.updateMatrix(entry->fState.fMatrix);
1502 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001503
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001504 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001505 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001506 entry = entry->fNext.get();
1507 }
1508 gsState.drainStack();
1509}
1510
reed@google.com5667afc2011-06-27 14:42:15 +00001511SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001512 SkDynamicMemoryWStream data;
1513 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1514 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001515 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001516
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001517 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1518 // colors the contentArea white before it starts drawing into it and
1519 // that currently acts as our clip.
1520 // Also, think about adding a transform here (or assume that the values
1521 // sent across account for that)
1522 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001523
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001524 // If the content area is the entire page, then we don't need to clip
1525 // the content area (PDF area clips to the page size). Otherwise,
1526 // we have to clip to the content area; we've already applied the
1527 // initial transform, so just clip to the device size.
1528 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001529 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1530 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001531 emit_clip(NULL, &r, &data);
1532 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001533
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001534 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001535
reed@google.com5667afc2011-06-27 14:42:15 +00001536 // potentially we could cache this SkData, and only rebuild it if we
1537 // see that our state has changed.
1538 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001539}
1540
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001541#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001542/* Draws an inverse filled path by using Path Ops to compute the positive
1543 * inverse using the current clip as the inverse bounds.
1544 * Return true if this was an inverse path and was properly handled,
1545 * otherwise returns false and the normal drawing routine should continue,
1546 * either as a (incorrect) fallback or because the path was not inverse
1547 * in the first place.
1548 */
1549bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001550 const SkPaint& paint, bool pathIsMutable,
1551 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001552 if (!origPath.isInverseFillType()) {
1553 return false;
1554 }
1555
1556 if (d.fClip->isEmpty()) {
1557 return false;
1558 }
1559
1560 SkPath modifiedPath;
1561 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1562 SkPaint noInversePaint(paint);
1563
1564 // Merge stroking operations into final path.
1565 if (SkPaint::kStroke_Style == paint.getStyle() ||
1566 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1567 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1568 if (doFillPath) {
1569 noInversePaint.setStyle(SkPaint::kFill_Style);
1570 noInversePaint.setStrokeWidth(0);
1571 pathPtr = &modifiedPath;
1572 } else {
1573 // To be consistent with the raster output, hairline strokes
1574 // are rendered as non-inverted.
1575 modifiedPath.toggleInverseFillType();
1576 drawPath(d, modifiedPath, paint, NULL, true);
1577 return true;
1578 }
1579 }
1580
1581 // Get bounds of clip in current transform space
1582 // (clip bounds are given in device space).
1583 SkRect bounds;
1584 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001585 SkMatrix totalMatrix = *d.fMatrix;
1586 if (prePathMatrix) {
1587 totalMatrix.preConcat(*prePathMatrix);
1588 }
1589 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001590 return false;
1591 }
1592 bounds.set(d.fClip->getBounds());
1593 transformInverse.mapRect(&bounds);
1594
1595 // Extend the bounds by the line width (plus some padding)
1596 // so the edge doesn't cause a visible stroke.
1597 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1598 paint.getStrokeWidth() + SK_Scalar1);
1599
1600 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1601 return false;
1602 }
1603
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001604 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001605 return true;
1606}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001607#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001608
epoger@google.comb58772f2013-03-08 09:09:10 +00001609bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1610 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001611 SkAnnotation* annotationInfo = p.getAnnotation();
1612 if (!annotationInfo) {
1613 return false;
1614 }
1615 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001616 if (urlData) {
1617 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001618 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001619 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001620 SkData* linkToName = annotationInfo->find(
1621 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001622 if (linkToName) {
1623 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001624 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001625 }
1626 return false;
1627}
1628
1629bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1630 const SkMatrix& matrix,
1631 const SkPaint& paint) {
1632 SkAnnotation* annotationInfo = paint.getAnnotation();
1633 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001634 return false;
1635 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001636 SkData* nameData = annotationInfo->find(
1637 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001638 if (nameData) {
1639 for (size_t i = 0; i < count; i++) {
1640 defineNamedDestination(nameData, points[i], matrix);
1641 }
reed@google.com44699382013-10-31 17:28:30 +00001642 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001643 }
1644 return false;
1645}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001646
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001647SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1648 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001649 SkMatrix transform = matrix;
1650 transform.postConcat(fInitialTransform);
1651 SkRect translatedRect;
1652 transform.mapRect(&translatedRect, r);
1653
reed@google.com2a006c12012-09-19 17:05:55 +00001654 if (NULL == fAnnotations) {
1655 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001656 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001657 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001658 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001659 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001660
epoger@google.comb58772f2013-03-08 09:09:10 +00001661 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001662 border->reserve(3);
1663 border->appendInt(0); // Horizontal corner radius.
1664 border->appendInt(0); // Vertical corner radius.
1665 border->appendInt(0); // Width, 0 = no border.
1666 annotation->insert("Border", border.get());
1667
epoger@google.comb58772f2013-03-08 09:09:10 +00001668 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001669 rect->reserve(4);
1670 rect->appendScalar(translatedRect.fLeft);
1671 rect->appendScalar(translatedRect.fTop);
1672 rect->appendScalar(translatedRect.fRight);
1673 rect->appendScalar(translatedRect.fBottom);
1674 annotation->insert("Rect", rect.get());
1675
epoger@google.comb58772f2013-03-08 09:09:10 +00001676 return annotation;
1677}
epoger@google.com1cad8982013-03-06 00:05:13 +00001678
epoger@google.comb58772f2013-03-08 09:09:10 +00001679void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1680 const SkMatrix& matrix) {
1681 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1682
1683 SkString url(static_cast<const char *>(urlData->data()),
1684 urlData->size() - 1);
1685 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1686 action->insertName("S", "URI");
1687 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1688 annotation->insert("A", action.get());
1689}
1690
1691void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1692 const SkMatrix& matrix) {
1693 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1694 SkString name(static_cast<const char *>(nameData->data()),
1695 nameData->size() - 1);
1696 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1697}
1698
1699struct NamedDestination {
1700 const SkData* nameData;
1701 SkPoint point;
1702
1703 NamedDestination(const SkData* nameData, const SkPoint& point)
1704 : nameData(nameData), point(point) {
1705 nameData->ref();
1706 }
1707
1708 ~NamedDestination() {
1709 nameData->unref();
1710 }
1711};
1712
1713void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1714 const SkMatrix& matrix) {
1715 SkMatrix transform = matrix;
1716 transform.postConcat(fInitialTransform);
1717 SkPoint translatedPoint;
1718 transform.mapXY(point.x(), point.y(), &translatedPoint);
1719 fNamedDestinations.push(
1720 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1721}
1722
1723void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1724 int nDest = fNamedDestinations.count();
1725 for (int i = 0; i < nDest; i++) {
1726 NamedDestination* dest = fNamedDestinations[i];
1727 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1728 pdfDest->reserve(5);
1729 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1730 pdfDest->appendName("XYZ");
1731 pdfDest->appendScalar(dest->point.x());
1732 pdfDest->appendScalar(dest->point.y());
1733 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001734 dict->insert(static_cast<const char *>(dest->nameData->data()),
1735 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001736 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001737}
1738
reed@google.comfc641d02012-09-20 17:52:20 +00001739SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1740 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001741 // We always draw the form xobjects that we create back into the device, so
1742 // we simply preserve the font usage instead of pulling it out and merging
1743 // it back in later.
1744 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001745 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001746 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001747}
1748
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001749void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1750 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001751 const SkClipStack* clipStack,
1752 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001753 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001754 bool invertClip) {
1755 if (clipRegion.isEmpty() && !invertClip) {
1756 return;
1757 }
1758
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001759 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1760 SkPDFGraphicState::GetSMaskGraphicState(
1761 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1762
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001763 SkMatrix identity;
1764 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001765 SkPaint paint;
1766 paint.setXfermodeMode(mode);
1767 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001768 if (!content.entry()) {
1769 return;
1770 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001771 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001772 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001773 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001774
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001775 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001776 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001777 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001778}
1779
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001780ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1781 const SkRegion& clipRegion,
1782 const SkMatrix& matrix,
1783 const SkPaint& paint,
1784 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001785 SkPDFFormXObject** dst) {
1786 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001787 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001788 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001789 }
1790
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001791 // The clip stack can come from an SkDraw where it is technically optional.
1792 SkClipStack synthesizedClipStack;
1793 if (clipStack == NULL) {
1794 if (clipRegion == fExistingClipRegion) {
1795 clipStack = &fExistingClipStack;
1796 } else {
1797 // GraphicStackState::updateClip expects the clip stack to have
1798 // fExistingClip as a prefix, so start there, then set the clip
1799 // to the passed region.
1800 synthesizedClipStack = fExistingClipStack;
1801 SkPath clipPath;
1802 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001803 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1804 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001805 clipStack = &synthesizedClipStack;
1806 }
1807 }
1808
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001809 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1810 if (paint.getXfermode()) {
1811 paint.getXfermode()->asMode(&xfermode);
1812 }
1813
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001814 // For the following modes, we want to handle source and destination
1815 // separately, so make an object of what's already there.
1816 if (xfermode == SkXfermode::kClear_Mode ||
1817 xfermode == SkXfermode::kSrc_Mode ||
1818 xfermode == SkXfermode::kSrcIn_Mode ||
1819 xfermode == SkXfermode::kDstIn_Mode ||
1820 xfermode == SkXfermode::kSrcOut_Mode ||
1821 xfermode == SkXfermode::kDstOut_Mode ||
1822 xfermode == SkXfermode::kSrcATop_Mode ||
1823 xfermode == SkXfermode::kDstATop_Mode ||
1824 xfermode == SkXfermode::kModulate_Mode) {
1825 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001826 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001827 SkASSERT(isContentEmpty());
1828 } else if (xfermode != SkXfermode::kSrc_Mode &&
1829 xfermode != SkXfermode::kSrcOut_Mode) {
1830 // Except for Src and SrcOut, if there isn't anything already there,
1831 // then we're done.
1832 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001833 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001834 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001835 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001836 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001837
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 // Dst xfer mode doesn't draw source at all.
1839 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001840 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001841 }
1842
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001843 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001844 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001845
1846 ContentEntry* lastContentEntry = getLastContentEntry();
1847 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1848 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001849 } else {
1850 newEntry.reset(new ContentEntry);
1851 entry = newEntry.get();
1852 }
1853
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001854 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001855 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001856 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1857 entry->fState.compareInitialState(lastContentEntry->fState)) {
1858 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001859 }
1860
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001861 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001862 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001863 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001864 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001865 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001866 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001867 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001868 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001869 lastContentEntry->fNext.reset(entry);
1870 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001871 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001872 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001873 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001874}
1875
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001876void SkPDFDevice::finishContentEntry(const SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001877 SkPDFFormXObject* dst,
1878 SkPath* shape) {
1879 if (xfermode != SkXfermode::kClear_Mode &&
1880 xfermode != SkXfermode::kSrc_Mode &&
1881 xfermode != SkXfermode::kSrcIn_Mode &&
1882 xfermode != SkXfermode::kDstIn_Mode &&
1883 xfermode != SkXfermode::kSrcOut_Mode &&
1884 xfermode != SkXfermode::kDstOut_Mode &&
1885 xfermode != SkXfermode::kSrcATop_Mode &&
1886 xfermode != SkXfermode::kDstATop_Mode &&
1887 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001888 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001889 return;
1890 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001891 if (!dst) {
1892 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1893 xfermode == SkXfermode::kSrcOut_Mode);
1894 return;
1895 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001896
1897 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001898 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001899 SkASSERT(!contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001900 // We have to make a copy of these here because changing the current
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001901 // content into a form-xobject will destroy them.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001902 SkClipStack clipStack = contentEntries->fState.fClipStack;
1903 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001904
reed@google.comfc641d02012-09-20 17:52:20 +00001905 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001906 if (isContentEmpty()) {
1907 SkASSERT(xfermode == SkXfermode::kClear_Mode);
1908 } else {
1909 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001910 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001911 }
1912
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001913 SkMatrix identity;
1914 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001915
1916 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1917 // without alpha.
1918 if (xfermode == SkXfermode::kSrcATop_Mode) {
1919 // TODO(vandebo): In order to properly support SrcATop we have to track
1920 // the shape of what's been drawn at all times. It's the intersection of
1921 // the non-transparent parts of the device and the outlines (shape) of
1922 // all images and devices drawn.
1923 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1924 &clipStack, clipRegion,
1925 SkXfermode::kSrcOver_Mode, true);
1926 } else {
1927 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1928 SkPDFFormXObject* dstMask = srcFormXObject.get();
1929 if (shape != NULL) {
1930 // Draw shape into a form-xobject.
1931 SkDraw d;
1932 d.fMatrix = &identity;
1933 d.fClip = &clipRegion;
1934 d.fClipStack = &clipStack;
1935 SkPaint filledPaint;
1936 filledPaint.setColor(SK_ColorBLACK);
1937 filledPaint.setStyle(SkPaint::kFill_Style);
1938 this->drawPath(d, *shape, filledPaint, NULL, true);
1939
1940 dstMaskStorage.reset(createFormXObjectFromDevice());
1941 dstMask = dstMaskStorage.get();
1942 }
1943 drawFormXObjectWithMask(addXObjectResource(dst), dstMask, &clipStack,
1944 clipRegion, SkXfermode::kSrcOver_Mode, true);
1945 }
1946
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001947 SkPaint stockPaint;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001948
1949 if (xfermode == SkXfermode::kClear_Mode) {
1950 return;
1951 } else if (xfermode == SkXfermode::kSrc_Mode ||
1952 xfermode == SkXfermode::kDstATop_Mode) {
1953 ScopedContentEntry content(this, &clipStack, clipRegion, identity,
1954 stockPaint);
1955 if (content.entry()) {
1956 SkPDFUtils::DrawFormXObject(
1957 this->addXObjectResource(srcFormXObject.get()),
1958 &content.entry()->fContent);
1959 }
1960 if (xfermode == SkXfermode::kSrc_Mode) {
1961 return;
1962 }
1963 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
1964 ScopedContentEntry content(this, &clipStack, clipRegion, identity,
1965 stockPaint);
1966 if (content.entry()) {
1967 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1968 &content.entry()->fContent);
1969 }
1970 }
1971
1972 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1973 xfermode == SkXfermode::kDstIn_Mode ||
1974 xfermode == SkXfermode::kSrcOut_Mode ||
1975 xfermode == SkXfermode::kDstOut_Mode ||
1976 xfermode == SkXfermode::kSrcATop_Mode ||
1977 xfermode == SkXfermode::kDstATop_Mode ||
1978 xfermode == SkXfermode::kModulate_Mode);
1979
1980 ScopedContentEntry inShapeContentEntry(this, &fExistingClipStack,
1981 fExistingClipRegion, identity,
1982 stockPaint);
1983 if (!inShapeContentEntry.entry()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001984 return;
1985 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001986
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001987 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001988 xfermode == SkXfermode::kSrcOut_Mode ||
1989 xfermode == SkXfermode::kSrcATop_Mode) {
1990 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1991 &clipStack, clipRegion,
1992 SkXfermode::kSrcOver_Mode,
1993 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001994 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001995 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1996 if (xfermode == SkXfermode::kModulate_Mode) {
1997 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1998 dst, &clipStack, clipRegion,
1999 SkXfermode::kSrcOver_Mode, false);
2000 mode = SkXfermode::kMultiply_Mode;
2001 }
2002 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
2003 &clipStack, clipRegion, mode,
2004 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002005 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002006}
2007
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002008bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002009 ContentEntry* contentEntries = getContentEntries()->get();
2010 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
2011 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002012 return true;
2013 }
2014 return false;
2015}
2016
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002017void SkPDFDevice::populateGraphicStateEntryFromPaint(
2018 const SkMatrix& matrix,
2019 const SkClipStack& clipStack,
2020 const SkRegion& clipRegion,
2021 const SkPaint& paint,
2022 bool hasText,
2023 GraphicStateEntry* entry) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002024 SkASSERT(paint.getPathEffect() == NULL);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002025
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002026 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
2027 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002028
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002029 entry->fMatrix = matrix;
2030 entry->fClipStack = clipStack;
2031 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002032 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2033 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002034
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002035 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002036 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002037 const SkShader* shader = paint.getShader();
2038 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002039 if (shader) {
2040 // PDF positions patterns relative to the initial transform, so
2041 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002042 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00002043 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002044
2045 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002046 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002047 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00002048
2049 // We need to apply the initial transform to bounds in order to get
2050 // bounds in a consistent coordinate system.
2051 SkRect boundsTemp;
2052 boundsTemp.set(bounds);
2053 fInitialTransform.mapRect(&boundsTemp);
2054 boundsTemp.roundOut(&bounds);
2055
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002056 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002057
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002058 if (pdfShader.get()) {
2059 // pdfShader has been canonicalized so we can directly compare
2060 // pointers.
2061 int resourceIndex = fShaderResources.find(pdfShader.get());
2062 if (resourceIndex < 0) {
2063 resourceIndex = fShaderResources.count();
2064 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002065 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002066 }
2067 entry->fShaderIndex = resourceIndex;
2068 } else {
2069 // A color shader is treated as an invalid shader so we don't have
2070 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002071 SkShader::GradientInfo gradientInfo;
2072 SkColor gradientColor;
2073 gradientInfo.fColors = &gradientColor;
2074 gradientInfo.fColorOffsets = NULL;
2075 gradientInfo.fColorCount = 1;
2076 if (shader->asAGradient(&gradientInfo) ==
2077 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002078 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2079 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002080 }
2081 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002082 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002083
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002084 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002085 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002086 newGraphicState.reset(
2087 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002088 } else {
2089 SkPaint newPaint = paint;
2090 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002091 newGraphicState.reset(
2092 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002093 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002094 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002095 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002096
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002097 if (hasText) {
2098 entry->fTextScaleX = paint.getTextScaleX();
2099 entry->fTextFill = paint.getStyle();
2100 } else {
2101 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002102 }
2103}
2104
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002105int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2106 // Assumes that gs has been canonicalized (so we can directly compare
2107 // pointers).
2108 int result = fGraphicStateResources.find(gs);
2109 if (result < 0) {
2110 result = fGraphicStateResources.count();
2111 fGraphicStateResources.push(gs);
2112 gs->ref();
2113 }
2114 return result;
2115}
2116
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002117int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2118 // Assumes that xobject has been canonicalized (so we can directly compare
2119 // pointers).
2120 int result = fXObjectResources.find(xObject);
2121 if (result < 0) {
2122 result = fXObjectResources.count();
2123 fXObjectResources.push(xObject);
2124 xObject->ref();
2125 }
2126 return result;
2127}
2128
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002129void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2130 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002131 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002132 if (contentEntry->fState.fFont == NULL ||
2133 contentEntry->fState.fTextSize != paint.getTextSize() ||
2134 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002135 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002136 contentEntry->fContent.writeText("/");
2137 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2138 SkPDFResourceDict::kFont_ResourceType,
2139 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002140 contentEntry->fContent.writeText(" ");
2141 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2142 contentEntry->fContent.writeText(" Tf\n");
2143 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002144 }
2145}
2146
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002147int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002148 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2149 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002150 int resourceIndex = fFontResources.find(newFont.get());
2151 if (resourceIndex < 0) {
2152 resourceIndex = fFontResources.count();
2153 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002154 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002155 }
2156 return resourceIndex;
2157}
2158
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002159void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002160 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002161 const SkRegion& origClipRegion,
2162 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002163 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002164 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002165 SkMatrix matrix = origMatrix;
2166 SkRegion perspectiveBounds;
2167 const SkRegion* clipRegion = &origClipRegion;
2168 SkBitmap perspectiveBitmap;
2169 const SkBitmap* bitmap = &origBitmap;
2170 SkBitmap tmpSubsetBitmap;
2171
2172 // Rasterize the bitmap using perspective in a new bitmap.
2173 if (origMatrix.hasPerspective()) {
2174 SkBitmap* subsetBitmap;
2175 if (srcRect) {
2176 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2177 return;
2178 }
2179 subsetBitmap = &tmpSubsetBitmap;
2180 } else {
2181 subsetBitmap = &tmpSubsetBitmap;
2182 *subsetBitmap = origBitmap;
2183 }
2184 srcRect = NULL;
2185
2186 // Transform the bitmap in the new space.
2187 SkPath perspectiveOutline;
2188 perspectiveOutline.addRect(
2189 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2190 SkIntToScalar(subsetBitmap->height())));
2191 perspectiveOutline.transform(origMatrix);
2192
2193 // TODO(edisonn): perf - use current clip too.
2194 // Retrieve the bounds of the new shape.
2195 SkRect bounds = perspectiveOutline.getBounds();
2196
2197 // TODO(edisonn): add DPI settings. Currently 1 pixel/point, which does
2198 // not look great, but it is not producing large PDFs.
2199
2200 // TODO(edisonn): A better approach would be to use a bitmap shader
2201 // (in clamp mode) and draw a rect over the entire bounding box. Then
2202 // intersect perspectiveOutline to the clip. That will avoid introducing
2203 // alpha to the image while still giving good behavior at the edge of
2204 // the image. Avoiding alpha will reduce the pdf size and generation
2205 // CPU time some.
2206
2207 perspectiveBitmap.setConfig(SkBitmap::kARGB_8888_Config,
2208 SkScalarCeilToInt(bounds.width()),
2209 SkScalarCeilToInt(bounds.height()));
2210 perspectiveBitmap.allocPixels();
2211 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2212
2213 SkBitmapDevice device(perspectiveBitmap);
2214 SkCanvas canvas(&device);
2215
2216 SkScalar deltaX = bounds.left();
2217 SkScalar deltaY = bounds.top();
2218
2219 SkMatrix offsetMatrix = origMatrix;
2220 offsetMatrix.postTranslate(-deltaX, -deltaY);
2221
2222 // Translate the draw in the new canvas, so we perfectly fit the
2223 // shape in the bitmap.
2224 canvas.setMatrix(offsetMatrix);
2225
2226 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2227
2228 // Make sure the final bits are in the bitmap.
2229 canvas.flush();
2230
2231 // In the new space, we use the identity matrix translated.
2232 matrix.setTranslate(deltaX, deltaY);
2233 perspectiveBounds.setRect(
2234 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2235 SkScalarFloorToInt(bounds.y()),
2236 SkScalarCeilToInt(bounds.width()),
2237 SkScalarCeilToInt(bounds.height())));
2238 clipRegion = &perspectiveBounds;
2239 srcRect = NULL;
2240 bitmap = &perspectiveBitmap;
2241 }
2242
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002243 SkMatrix scaled;
2244 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002245 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2246 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002247 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002248 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002249 scaled.postScale(SkIntToScalar(subset.width()),
2250 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002251 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002252 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002253 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2254 return;
2255 }
2256 if (content.needShape()) {
2257 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002258 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2259 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002260 shape.transform(matrix);
2261 content.setShape(shape);
2262 }
2263 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002264 return;
2265 }
2266
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002267 SkAutoTUnref<SkPDFImage> image(
2268 SkPDFImage::CreateImage(*bitmap, subset, fEncoder));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002269 if (!image) {
2270 return;
2271 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002272
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002273 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002274 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002275}
reed@google.com982cb872011-12-07 18:34:08 +00002276
2277bool SkPDFDevice::onReadPixels(const SkBitmap& bitmap, int x, int y,
2278 SkCanvas::Config8888) {
2279 return false;
2280}
reed@google.comb55deeb2012-01-06 14:43:09 +00002281
2282bool SkPDFDevice::allowImageFilter(SkImageFilter*) {
2283 return false;
2284}