Plumb dst color space in many places, rather than "mode"
[platform/upstream/libSkiaSharp.git] / src / pdf / SkPDFDevice.cpp
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "SkPDFDevice.h"
9
10 #include "SkAdvancedTypefaceMetrics.h"
11 #include "SkAnnotationKeys.h"
12 #include "SkBitmapDevice.h"
13 #include "SkBitmapKey.h"
14 #include "SkColor.h"
15 #include "SkColorFilter.h"
16 #include "SkDraw.h"
17 #include "SkDrawFilter.h"
18 #include "SkGlyphCache.h"
19 #include "SkImageFilterCache.h"
20 #include "SkMakeUnique.h"
21 #include "SkPath.h"
22 #include "SkPathEffect.h"
23 #include "SkPathOps.h"
24 #include "SkPDFBitmap.h"
25 #include "SkPDFCanon.h"
26 #include "SkPDFDocument.h"
27 #include "SkPDFFont.h"
28 #include "SkPDFFormXObject.h"
29 #include "SkPDFGraphicState.h"
30 #include "SkPDFResourceDict.h"
31 #include "SkPDFShader.h"
32 #include "SkPDFTypes.h"
33 #include "SkPDFUtils.h"
34 #include "SkPixelRef.h"
35 #include "SkRasterClip.h"
36 #include "SkRRect.h"
37 #include "SkScopeExit.h"
38 #include "SkString.h"
39 #include "SkSurface.h"
40 #include "SkTemplates.h"
41 #include "SkTextBlobRunIterator.h"
42 #include "SkTextFormatParams.h"
43 #include "SkUtils.h"
44 #include "SkXfermodeInterpretation.h"
45
46 #define DPI_FOR_RASTER_SCALE_ONE 72
47
48 // Utility functions
49
50 // If the paint will definitely draw opaquely, replace kSrc with
51 // kSrcOver.  http://crbug.com/473572
52 static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
53     if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
54         paint->setBlendMode(SkBlendMode::kSrcOver);
55     }
56 }
57
58 static void emit_pdf_color(SkColor color, SkWStream* result) {
59     SkASSERT(SkColorGetA(color) == 0xFF);  // We handle alpha elsewhere.
60     SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
61     result->writeText(" ");
62     SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
63     result->writeText(" ");
64     SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
65     result->writeText(" ");
66 }
67
68 static SkPaint calculate_text_paint(const SkPaint& paint) {
69     SkPaint result = paint;
70     if (result.isFakeBoldText()) {
71         SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
72                                                     kStdFakeBoldInterpKeys,
73                                                     kStdFakeBoldInterpValues,
74                                                     kStdFakeBoldInterpLength);
75         SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
76         if (result.getStyle() == SkPaint::kFill_Style) {
77             result.setStyle(SkPaint::kStrokeAndFill_Style);
78         } else {
79             width += result.getStrokeWidth();
80         }
81         result.setStrokeWidth(width);
82     }
83     return result;
84 }
85
86 static SkImageSubset make_image_subset(const SkBitmap& bitmap) {
87     SkASSERT(!bitmap.drawsNothing());
88     SkIRect subset = bitmap.getSubset();
89     SkAutoLockPixels autoLockPixels(bitmap);
90     SkASSERT(bitmap.pixelRef());
91     SkBitmap tmp;
92     tmp.setInfo(bitmap.pixelRef()->info(), bitmap.rowBytes());
93     tmp.setPixelRef(bitmap.pixelRef());
94     tmp.lockPixels();
95     auto img = SkImage::MakeFromBitmap(tmp);
96     if (img) {
97         SkASSERT(!bitmap.isImmutable() || img->uniqueID() == bitmap.getGenerationID());
98         SkASSERT(img->bounds().contains(subset));
99     }
100     SkImageSubset imageSubset(std::move(img), subset);
101     // SkImage::MakeFromBitmap only preserves genID for immutable
102     // bitmaps.  Use the bitmap's original ID for de-duping.
103     imageSubset.setID(bitmap.getGenerationID());
104     return imageSubset;
105 }
106
107 SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
108     : fColor(SK_ColorBLACK)
109     , fTextScaleX(SK_Scalar1)
110     , fTextFill(SkPaint::kFill_Style)
111     , fShaderIndex(-1)
112     , fGraphicStateIndex(-1) {
113     fMatrix.reset();
114 }
115
116 bool SkPDFDevice::GraphicStateEntry::compareInitialState(
117         const GraphicStateEntry& cur) {
118     return fColor == cur.fColor &&
119            fShaderIndex == cur.fShaderIndex &&
120            fGraphicStateIndex == cur.fGraphicStateIndex &&
121            fMatrix == cur.fMatrix &&
122            fClipStack == cur.fClipStack &&
123            (fTextScaleX == 0 ||
124                (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
125 }
126
127 class GraphicStackState {
128 public:
129     GraphicStackState(const SkClipStack& existingClipStack,
130                       const SkRegion& existingClipRegion,
131                       SkWStream* contentStream)
132             : fStackDepth(0),
133               fContentStream(contentStream) {
134         fEntries[0].fClipStack = existingClipStack;
135         fEntries[0].fClipRegion = existingClipRegion;
136     }
137
138     void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
139                     const SkPoint& translation);
140     void updateMatrix(const SkMatrix& matrix);
141     void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
142
143     void drainStack();
144
145 private:
146     void push();
147     void pop();
148     SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
149
150     // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
151     static const int kMaxStackDepth = 12;
152     SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
153     int fStackDepth;
154     SkWStream* fContentStream;
155 };
156
157 void GraphicStackState::drainStack() {
158     while (fStackDepth) {
159         pop();
160     }
161 }
162
163 void GraphicStackState::push() {
164     SkASSERT(fStackDepth < kMaxStackDepth);
165     fContentStream->writeText("q\n");
166     fStackDepth++;
167     fEntries[fStackDepth] = fEntries[fStackDepth - 1];
168 }
169
170 void GraphicStackState::pop() {
171     SkASSERT(fStackDepth > 0);
172     fContentStream->writeText("Q\n");
173     fStackDepth--;
174 }
175
176 /* Calculate an inverted path's equivalent non-inverted path, given the
177  * canvas bounds.
178  * outPath may alias with invPath (since this is supported by PathOps).
179  */
180 static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
181                                    SkPath* outPath) {
182     SkASSERT(invPath.isInverseFillType());
183
184     SkPath clipPath;
185     clipPath.addRect(bounds);
186
187     return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
188 }
189
190 // Sanity check the numerical values of the SkRegion ops and PathOps ops
191 // enums so region_op_to_pathops_op can do a straight passthrough cast.
192 // If these are failing, it may be necessary to make region_op_to_pathops_op
193 // do more.
194 static_assert(SkRegion::kDifference_Op == (int)kDifference_SkPathOp, "region_pathop_mismatch");
195 static_assert(SkRegion::kIntersect_Op == (int)kIntersect_SkPathOp, "region_pathop_mismatch");
196 static_assert(SkRegion::kUnion_Op == (int)kUnion_SkPathOp, "region_pathop_mismatch");
197 static_assert(SkRegion::kXOR_Op == (int)kXOR_SkPathOp, "region_pathop_mismatch");
198 static_assert(SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkPathOp,
199               "region_pathop_mismatch");
200
201 static SkPathOp region_op_to_pathops_op(SkClipOp op) {
202     SkASSERT(op >= 0);
203     SkASSERT(op <= kReverseDifference_SkClipOp);
204     return (SkPathOp)op;
205 }
206
207 /* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
208  * Returns true if successful, or false if not successful.
209  * If successful, the resulting clip is stored in outClipPath.
210  * If not successful, outClipPath is undefined, and a fallback method
211  * should be used.
212  */
213 static bool get_clip_stack_path(const SkMatrix& transform,
214                                 const SkClipStack& clipStack,
215                                 const SkRegion& clipRegion,
216                                 SkPath* outClipPath) {
217     outClipPath->reset();
218     outClipPath->setFillType(SkPath::kInverseWinding_FillType);
219
220     const SkClipStack::Element* clipEntry;
221     SkClipStack::Iter iter;
222     iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
223     for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
224         SkPath entryPath;
225         if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
226             outClipPath->reset();
227             outClipPath->setFillType(SkPath::kInverseWinding_FillType);
228             continue;
229         } else {
230             clipEntry->asPath(&entryPath);
231         }
232         entryPath.transform(transform);
233
234         if (kReplace_SkClipOp == clipEntry->getOp()) {
235             *outClipPath = entryPath;
236         } else {
237             SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
238             if (!Op(*outClipPath, entryPath, op, outClipPath)) {
239                 return false;
240             }
241         }
242     }
243
244     if (outClipPath->isInverseFillType()) {
245         // The bounds are slightly outset to ensure this is correct in the
246         // face of floating-point accuracy and possible SkRegion bitmap
247         // approximations.
248         SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
249         clipBounds.outset(SK_Scalar1, SK_Scalar1);
250         if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
251             return false;
252         }
253     }
254     return true;
255 }
256
257 // TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
258 // graphic state stack, and the fact that we can know all the clips used
259 // on the page to optimize this.
260 void GraphicStackState::updateClip(const SkClipStack& clipStack,
261                                    const SkRegion& clipRegion,
262                                    const SkPoint& translation) {
263     if (clipStack == currentEntry()->fClipStack) {
264         return;
265     }
266
267     while (fStackDepth > 0) {
268         pop();
269         if (clipStack == currentEntry()->fClipStack) {
270             return;
271         }
272     }
273     push();
274
275     currentEntry()->fClipStack = clipStack;
276     currentEntry()->fClipRegion = clipRegion;
277
278     SkMatrix transform;
279     transform.setTranslate(translation.fX, translation.fY);
280
281     SkPath clipPath;
282     if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
283         SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
284         SkPath::FillType clipFill = clipPath.getFillType();
285         NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
286         NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
287         if (clipFill == SkPath::kEvenOdd_FillType) {
288             fContentStream->writeText("W* n\n");
289         } else {
290             fContentStream->writeText("W n\n");
291         }
292     }
293     // If Op() fails (pathological case; e.g. input values are
294     // extremely large or NaN), emit no clip at all.
295 }
296
297 void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
298     if (matrix == currentEntry()->fMatrix) {
299         return;
300     }
301
302     if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
303         SkASSERT(fStackDepth > 0);
304         SkASSERT(fEntries[fStackDepth].fClipStack ==
305                  fEntries[fStackDepth -1].fClipStack);
306         pop();
307
308         SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
309     }
310     if (matrix.getType() == SkMatrix::kIdentity_Mask) {
311         return;
312     }
313
314     push();
315     SkPDFUtils::AppendTransform(matrix, fContentStream);
316     currentEntry()->fMatrix = matrix;
317 }
318
319 void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
320     // PDF treats a shader as a color, so we only set one or the other.
321     if (state.fShaderIndex >= 0) {
322         if (state.fShaderIndex != currentEntry()->fShaderIndex) {
323             SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
324             currentEntry()->fShaderIndex = state.fShaderIndex;
325         }
326     } else {
327         if (state.fColor != currentEntry()->fColor ||
328                 currentEntry()->fShaderIndex >= 0) {
329             emit_pdf_color(state.fColor, fContentStream);
330             fContentStream->writeText("RG ");
331             emit_pdf_color(state.fColor, fContentStream);
332             fContentStream->writeText("rg\n");
333             currentEntry()->fColor = state.fColor;
334             currentEntry()->fShaderIndex = -1;
335         }
336     }
337
338     if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
339         SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
340         currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
341     }
342
343     if (state.fTextScaleX) {
344         if (state.fTextScaleX != currentEntry()->fTextScaleX) {
345             SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
346                                             SkIntToScalar(100));
347             SkPDFUtils::AppendScalar(pdfScale, fContentStream);
348             fContentStream->writeText(" Tz\n");
349             currentEntry()->fTextScaleX = state.fTextScaleX;
350         }
351         if (state.fTextFill != currentEntry()->fTextFill) {
352             static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
353             static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
354             static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
355             fContentStream->writeDecAsText(state.fTextFill);
356             fContentStream->writeText(" Tr\n");
357             currentEntry()->fTextFill = state.fTextFill;
358         }
359     }
360 }
361
362 static bool not_supported_for_layers(const SkPaint& layerPaint) {
363     // PDF does not support image filters, so render them on CPU.
364     // Note that this rendering is done at "screen" resolution (100dpi), not
365     // printer resolution.
366     // TODO: It may be possible to express some filters natively using PDF
367     // to improve quality and file size (https://bug.skia.org/3043)
368
369     // TODO: should we return true if there is a colorfilter?
370     return layerPaint.getImageFilter() != nullptr;
371 }
372
373 SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
374     if (layerPaint && not_supported_for_layers(*layerPaint)) {
375         // need to return a raster device, which we will detect in drawDevice()
376         return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
377     }
378     SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
379     return SkPDFDevice::Create(size, fRasterDpi, fDocument);
380 }
381
382 SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
383
384
385
386 // A helper class to automatically finish a ContentEntry at the end of a
387 // drawing method and maintain the state needed between set up and finish.
388 class ScopedContentEntry {
389 public:
390     ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
391                        const SkPaint& paint, bool hasText = false)
392         : fDevice(device),
393           fContentEntry(nullptr),
394           fBlendMode(SkBlendMode::kSrcOver),
395           fDstFormXObject(nullptr) {
396         init(draw.fClipStack, draw.fRC->bwRgn(), *draw.fMatrix, paint, hasText);
397     }
398     ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
399                        const SkRegion& clipRegion, const SkMatrix& matrix,
400                        const SkPaint& paint, bool hasText = false)
401         : fDevice(device),
402           fContentEntry(nullptr),
403           fBlendMode(SkBlendMode::kSrcOver),
404           fDstFormXObject(nullptr) {
405         init(clipStack, clipRegion, matrix, paint, hasText);
406     }
407
408     ~ScopedContentEntry() {
409         if (fContentEntry) {
410             SkPath* shape = &fShape;
411             if (shape->isEmpty()) {
412                 shape = nullptr;
413             }
414             fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
415         }
416     }
417
418     SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
419
420     /* Returns true when we explicitly need the shape of the drawing. */
421     bool needShape() {
422         switch (fBlendMode) {
423             case SkBlendMode::kClear:
424             case SkBlendMode::kSrc:
425             case SkBlendMode::kSrcIn:
426             case SkBlendMode::kSrcOut:
427             case SkBlendMode::kDstIn:
428             case SkBlendMode::kDstOut:
429             case SkBlendMode::kSrcATop:
430             case SkBlendMode::kDstATop:
431             case SkBlendMode::kModulate:
432                 return true;
433             default:
434                 return false;
435         }
436     }
437
438     /* Returns true unless we only need the shape of the drawing. */
439     bool needSource() {
440         if (fBlendMode == SkBlendMode::kClear) {
441             return false;
442         }
443         return true;
444     }
445
446     /* If the shape is different than the alpha component of the content, then
447      * setShape should be called with the shape.  In particular, images and
448      * devices have rectangular shape.
449      */
450     void setShape(const SkPath& shape) {
451         fShape = shape;
452     }
453
454 private:
455     SkPDFDevice* fDevice;
456     SkPDFDevice::ContentEntry* fContentEntry;
457     SkBlendMode fBlendMode;
458     sk_sp<SkPDFObject> fDstFormXObject;
459     SkPath fShape;
460
461     void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
462               const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
463         // Shape has to be flatten before we get here.
464         if (matrix.hasPerspective()) {
465             NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
466             return;
467         }
468         fBlendMode = paint.getBlendMode();
469         fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
470                                                    matrix, paint, hasText,
471                                                    &fDstFormXObject);
472     }
473 };
474
475 ////////////////////////////////////////////////////////////////////////////////
476
477 SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
478     : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
479                 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
480     , fPageSize(pageSize)
481     , fExistingClipRegion(SkIRect::MakeSize(pageSize))
482     , fRasterDpi(rasterDpi)
483     , fDocument(doc) {
484     SkASSERT(pageSize.width() > 0);
485     SkASSERT(pageSize.height() > 0);
486
487     if (flip) {
488         // Skia generally uses the top left as the origin but PDF
489         // natively has the origin at the bottom left. This matrix
490         // corrects for that.  But that only needs to be done once, we
491         // don't do it when layering.
492         fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
493         fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
494     } else {
495         fInitialTransform.setIdentity();
496     }
497 }
498
499 SkPDFDevice::~SkPDFDevice() {
500     this->cleanUp();
501 }
502
503 void SkPDFDevice::init() {
504     fContentEntries.reset();
505 }
506
507 void SkPDFDevice::cleanUp() {
508     fGraphicStateResources.unrefAll();
509     fXObjectResources.unrefAll();
510     fFontResources.unrefAll();
511     fShaderResources.unrefAll();
512 }
513
514 void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
515                                  SkData* value) {
516     if (0 == rect.width() && 0 == rect.height()) {
517         handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
518     } else {
519         SkPath path;
520         path.addRect(rect);
521         handlePathAnnotation(path, d, key, value);
522     }
523 }
524
525 void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
526     SkPaint newPaint = paint;
527     replace_srcmode_on_opaque_paint(&newPaint);
528
529     newPaint.setStyle(SkPaint::kFill_Style);
530     ScopedContentEntry content(this, d, newPaint);
531     internalDrawPaint(newPaint, content.entry());
532 }
533
534 void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
535                                     SkPDFDevice::ContentEntry* contentEntry) {
536     if (!contentEntry) {
537         return;
538     }
539     SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
540                                  SkIntToScalar(this->height()));
541     SkMatrix inverse;
542     if (!contentEntry->fState.fMatrix.invert(&inverse)) {
543         return;
544     }
545     inverse.mapRect(&bbox);
546
547     SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
548     SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
549                           &contentEntry->fContent);
550 }
551
552 void SkPDFDevice::drawPoints(const SkDraw& d,
553                              SkCanvas::PointMode mode,
554                              size_t count,
555                              const SkPoint* points,
556                              const SkPaint& srcPaint) {
557     SkPaint passedPaint = srcPaint;
558     replace_srcmode_on_opaque_paint(&passedPaint);
559
560     if (count == 0) {
561         return;
562     }
563
564     // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
565     // We only use this when there's a path effect because of the overhead
566     // of multiple calls to setUpContentEntry it causes.
567     if (passedPaint.getPathEffect()) {
568         if (d.fRC->isEmpty()) {
569             return;
570         }
571         SkDraw pointDraw(d);
572         pointDraw.fDevice = this;
573         pointDraw.drawPoints(mode, count, points, passedPaint, true);
574         return;
575     }
576
577     const SkPaint* paint = &passedPaint;
578     SkPaint modifiedPaint;
579
580     if (mode == SkCanvas::kPoints_PointMode &&
581             paint->getStrokeCap() != SkPaint::kRound_Cap) {
582         modifiedPaint = *paint;
583         paint = &modifiedPaint;
584         if (paint->getStrokeWidth()) {
585             // PDF won't draw a single point with square/butt caps because the
586             // orientation is ambiguous.  Draw a rectangle instead.
587             modifiedPaint.setStyle(SkPaint::kFill_Style);
588             SkScalar strokeWidth = paint->getStrokeWidth();
589             SkScalar halfStroke = SkScalarHalf(strokeWidth);
590             for (size_t i = 0; i < count; i++) {
591                 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
592                 r.inset(-halfStroke, -halfStroke);
593                 drawRect(d, r, modifiedPaint);
594             }
595             return;
596         } else {
597             modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
598         }
599     }
600
601     ScopedContentEntry content(this, d, *paint);
602     if (!content.entry()) {
603         return;
604     }
605
606     switch (mode) {
607         case SkCanvas::kPolygon_PointMode:
608             SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
609                                &content.entry()->fContent);
610             for (size_t i = 1; i < count; i++) {
611                 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
612                                        &content.entry()->fContent);
613             }
614             SkPDFUtils::StrokePath(&content.entry()->fContent);
615             break;
616         case SkCanvas::kLines_PointMode:
617             for (size_t i = 0; i < count/2; i++) {
618                 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
619                                    &content.entry()->fContent);
620                 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
621                                        points[i * 2 + 1].fY,
622                                        &content.entry()->fContent);
623                 SkPDFUtils::StrokePath(&content.entry()->fContent);
624             }
625             break;
626         case SkCanvas::kPoints_PointMode:
627             SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
628             for (size_t i = 0; i < count; i++) {
629                 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
630                                    &content.entry()->fContent);
631                 SkPDFUtils::ClosePath(&content.entry()->fContent);
632                 SkPDFUtils::StrokePath(&content.entry()->fContent);
633             }
634             break;
635         default:
636             SkASSERT(false);
637     }
638 }
639
640 static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
641     auto annotation = sk_make_sp<SkPDFDict>("Annot");
642     annotation->insertName("Subtype", "Link");
643     annotation->insertInt("F", 4);  // required by ISO 19005
644
645     auto border = sk_make_sp<SkPDFArray>();
646     border->reserve(3);
647     border->appendInt(0);  // Horizontal corner radius.
648     border->appendInt(0);  // Vertical corner radius.
649     border->appendInt(0);  // Width, 0 = no border.
650     annotation->insertObject("Border", std::move(border));
651
652     auto rect = sk_make_sp<SkPDFArray>();
653     rect->reserve(4);
654     rect->appendScalar(translatedRect.fLeft);
655     rect->appendScalar(translatedRect.fTop);
656     rect->appendScalar(translatedRect.fRight);
657     rect->appendScalar(translatedRect.fBottom);
658     annotation->insertObject("Rect", std::move(rect));
659
660     return annotation;
661 }
662
663 static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
664     sk_sp<SkPDFDict> annotation = create_link_annotation(r);
665     SkString url(static_cast<const char *>(urlData->data()),
666                  urlData->size() - 1);
667     auto action = sk_make_sp<SkPDFDict>("Action");
668     action->insertName("S", "URI");
669     action->insertString("URI", url);
670     annotation->insertObject("A", std::move(action));
671     return annotation;
672 }
673
674 static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
675                                                const SkRect& r) {
676     sk_sp<SkPDFDict> annotation = create_link_annotation(r);
677     SkString name(static_cast<const char *>(nameData->data()),
678                   nameData->size() - 1);
679     annotation->insertName("Dest", name);
680     return annotation;
681 }
682
683 void SkPDFDevice::drawRect(const SkDraw& d,
684                            const SkRect& rect,
685                            const SkPaint& srcPaint) {
686     SkPaint paint = srcPaint;
687     replace_srcmode_on_opaque_paint(&paint);
688     SkRect r = rect;
689     r.sort();
690
691     if (paint.getPathEffect()) {
692         if (d.fRC->isEmpty()) {
693             return;
694         }
695         SkPath path;
696         path.addRect(r);
697         drawPath(d, path, paint, nullptr, true);
698         return;
699     }
700
701     ScopedContentEntry content(this, d, paint);
702     if (!content.entry()) {
703         return;
704     }
705     SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
706     SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
707                           &content.entry()->fContent);
708 }
709
710 void SkPDFDevice::drawRRect(const SkDraw& draw,
711                             const SkRRect& rrect,
712                             const SkPaint& srcPaint) {
713     SkPaint paint = srcPaint;
714     replace_srcmode_on_opaque_paint(&paint);
715     SkPath  path;
716     path.addRRect(rrect);
717     this->drawPath(draw, path, paint, nullptr, true);
718 }
719
720 void SkPDFDevice::drawOval(const SkDraw& draw,
721                            const SkRect& oval,
722                            const SkPaint& srcPaint) {
723     SkPaint paint = srcPaint;
724     replace_srcmode_on_opaque_paint(&paint);
725     SkPath  path;
726     path.addOval(oval);
727     this->drawPath(draw, path, paint, nullptr, true);
728 }
729
730 void SkPDFDevice::drawPath(const SkDraw& d,
731                            const SkPath& origPath,
732                            const SkPaint& srcPaint,
733                            const SkMatrix* prePathMatrix,
734                            bool pathIsMutable) {
735     SkPaint paint = srcPaint;
736     replace_srcmode_on_opaque_paint(&paint);
737     SkPath modifiedPath;
738     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
739
740     SkMatrix matrix = *d.fMatrix;
741     if (prePathMatrix) {
742         if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
743             if (!pathIsMutable) {
744                 pathPtr = &modifiedPath;
745                 pathIsMutable = true;
746             }
747             origPath.transform(*prePathMatrix, pathPtr);
748         } else {
749             matrix.preConcat(*prePathMatrix);
750         }
751     }
752
753     if (paint.getPathEffect()) {
754         if (d.fRC->isEmpty()) {
755             return;
756         }
757         if (!pathIsMutable) {
758             pathPtr = &modifiedPath;
759             pathIsMutable = true;
760         }
761         bool fill = paint.getFillPath(origPath, pathPtr);
762
763         SkPaint noEffectPaint(paint);
764         noEffectPaint.setPathEffect(nullptr);
765         if (fill) {
766             noEffectPaint.setStyle(SkPaint::kFill_Style);
767         } else {
768             noEffectPaint.setStyle(SkPaint::kStroke_Style);
769             noEffectPaint.setStrokeWidth(0);
770         }
771         drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
772         return;
773     }
774
775     if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
776         return;
777     }
778
779     ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
780     if (!content.entry()) {
781         return;
782     }
783     bool consumeDegeratePathSegments =
784            paint.getStyle() == SkPaint::kFill_Style ||
785            (paint.getStrokeCap() != SkPaint::kRound_Cap &&
786             paint.getStrokeCap() != SkPaint::kSquare_Cap);
787     SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
788                          consumeDegeratePathSegments,
789                          &content.entry()->fContent);
790     SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
791                           &content.entry()->fContent);
792 }
793
794
795 void SkPDFDevice::drawImageRect(const SkDraw& d,
796                                 const SkImage* image,
797                                 const SkRect* src,
798                                 const SkRect& dst,
799                                 const SkPaint& srcPaint,
800                                 SkCanvas::SrcRectConstraint) {
801     if (!image) {
802         return;
803     }
804     SkIRect bounds = image->bounds();
805     SkPaint paint = srcPaint;
806     if (image->isOpaque()) {
807         replace_srcmode_on_opaque_paint(&paint);
808     }
809     SkRect srcRect = src ? *src : SkRect::Make(bounds);
810     SkMatrix transform;
811     transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
812     if (src) {
813         if (!srcRect.intersect(SkRect::Make(bounds))) {
814             return;
815         }
816         srcRect.roundOut(&bounds);
817         transform.preTranslate(SkIntToScalar(bounds.x()),
818                                SkIntToScalar(bounds.y()));
819     }
820     SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)), bounds);
821     if (!imageSubset.isValid()) {
822         return;
823     }
824     transform.postConcat(*d.fMatrix);
825     this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
826                             std::move(imageSubset), paint);
827 }
828
829 void SkPDFDevice::drawBitmapRect(const SkDraw& d,
830                                  const SkBitmap& bitmap,
831                                  const SkRect* src,
832                                  const SkRect& dst,
833                                 const SkPaint& srcPaint,
834                                 SkCanvas::SrcRectConstraint) {
835     if (bitmap.drawsNothing()) {
836         return;
837     }
838     SkIRect bounds = bitmap.bounds();
839     SkPaint paint = srcPaint;
840     if (bitmap.isOpaque()) {
841         replace_srcmode_on_opaque_paint(&paint);
842     }
843     SkRect srcRect = src ? *src : SkRect::Make(bounds);
844     SkMatrix transform;
845     transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
846     if (src) {
847         if (!srcRect.intersect(SkRect::Make(bounds))) {
848             return;
849         }
850         srcRect.roundOut(&bounds);
851         transform.preTranslate(SkIntToScalar(bounds.x()),
852                                SkIntToScalar(bounds.y()));
853     }
854     SkBitmap bitmapSubset;
855     if (!bitmap.extractSubset(&bitmapSubset, bounds)) {
856         return;
857     }
858     SkImageSubset imageSubset = make_image_subset(bitmapSubset);
859     if (!imageSubset.isValid()) {
860         return;
861     }
862     transform.postConcat(*d.fMatrix);
863     this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
864                             std::move(imageSubset), paint);
865 }
866
867 void SkPDFDevice::drawBitmap(const SkDraw& d,
868                              const SkBitmap& bitmap,
869                              const SkMatrix& matrix,
870                              const SkPaint& srcPaint) {
871     if (bitmap.drawsNothing() || d.fRC->isEmpty()) {
872         return;
873     }
874     SkPaint paint = srcPaint;
875     if (bitmap.isOpaque()) {
876         replace_srcmode_on_opaque_paint(&paint);
877     }
878     SkImageSubset imageSubset = make_image_subset(bitmap);
879     if (!imageSubset.isValid()) {
880         return;
881     }
882     SkMatrix transform = matrix;
883     transform.postConcat(*d.fMatrix);
884     this->internalDrawImage(
885             transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
886 }
887
888 void SkPDFDevice::drawSprite(const SkDraw& d,
889                              const SkBitmap& bitmap,
890                              int x,
891                              int y,
892                              const SkPaint& srcPaint) {
893     if (bitmap.drawsNothing() || d.fRC->isEmpty()) {
894         return;
895     }
896     SkPaint paint = srcPaint;
897     if (bitmap.isOpaque()) {
898         replace_srcmode_on_opaque_paint(&paint);
899     }
900     SkImageSubset imageSubset = make_image_subset(bitmap);
901     if (!imageSubset.isValid()) {
902         return;
903     }
904     SkMatrix transform = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
905     this->internalDrawImage(
906             transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
907 }
908
909 void SkPDFDevice::drawImage(const SkDraw& draw,
910                             const SkImage* image,
911                             SkScalar x,
912                             SkScalar y,
913                             const SkPaint& srcPaint) {
914     SkPaint paint = srcPaint;
915     if (!image) {
916         return;
917     }
918     if (image->isOpaque()) {
919         replace_srcmode_on_opaque_paint(&paint);
920     }
921     if (draw.fRC->isEmpty()) {
922         return;
923     }
924     SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)));
925     if (!imageSubset.isValid()) {
926         return;
927     }
928     SkMatrix transform = SkMatrix::MakeTrans(x, y);
929     transform.postConcat(*draw.fMatrix);
930     this->internalDrawImage(
931             transform, draw.fClipStack, draw.fRC->bwRgn(), std::move(imageSubset), paint);
932 }
933
934 namespace {
935 class GlyphPositioner {
936 public:
937     GlyphPositioner(SkDynamicMemoryWStream* content,
938                     SkScalar textSkewX,
939                     bool wideChars,
940                     bool defaultPositioning,
941                     SkPoint origin)
942         : fContent(content)
943         , fCurrentMatrixOrigin(origin)
944         , fTextSkewX(textSkewX)
945         , fWideChars(wideChars)
946         , fDefaultPositioning(defaultPositioning) {
947     }
948     ~GlyphPositioner() { this->flush(); }
949     void flush() {
950         if (fInText) {
951             fContent->writeText("> Tj\n");
952             fInText = false;
953         }
954     }
955     void writeGlyph(SkPoint xy,
956                     SkScalar advanceWidth,
957                     uint16_t glyph) {
958         if (!fInitialized) {
959             // Flip the text about the x-axis to account for origin swap and include
960             // the passed parameters.
961             fContent->writeText("1 0 ");
962             SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
963             fContent->writeText(" -1 ");
964             SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
965             fContent->writeText(" ");
966             SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
967             fContent->writeText(" Tm\n");
968             fCurrentMatrixOrigin.set(0.0f, 0.0f);
969             fInitialized = true;
970         }
971 #ifdef SK_BUILD_FOR_WIN
972         const bool kAlwaysPosition = true;
973 #else
974         const bool kAlwaysPosition = false;
975 #endif
976         if (!fDefaultPositioning) {
977             SkPoint position = xy - fCurrentMatrixOrigin;
978             if (kAlwaysPosition || position != SkPoint{fXAdvance, 0}) {
979                 this->flush();
980                 SkPDFUtils::AppendScalar(position.x(), fContent);
981                 fContent->writeText(" ");
982                 SkPDFUtils::AppendScalar(-position.y(), fContent);
983                 fContent->writeText(" Td ");
984                 fCurrentMatrixOrigin = xy;
985                 fXAdvance = 0;
986             }
987             fXAdvance += advanceWidth;
988         }
989         if (!fInText) {
990             fContent->writeText("<");
991             fInText = true;
992         }
993         if (fWideChars) {
994             SkPDFUtils::WriteUInt16BE(fContent, glyph);
995         } else {
996             SkASSERT(0 == glyph >> 8);
997             SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
998         }
999     }
1000
1001 private:
1002     SkDynamicMemoryWStream* fContent;
1003     SkPoint fCurrentMatrixOrigin;
1004     SkScalar fXAdvance = 0.0f;
1005     SkScalar fTextSkewX;
1006     bool fWideChars;
1007     bool fInText = false;
1008     bool fInitialized = false;
1009     const bool fDefaultPositioning;
1010 };
1011
1012 /** Given the m-to-n glyph-to-character mapping data (as returned by
1013     harfbuzz), iterate over the clusters. */
1014 class Clusterator {
1015 public:
1016     Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1017     explicit Clusterator(uint32_t glyphCount)
1018         : fClusters(nullptr)
1019         , fUtf8Text(nullptr)
1020         , fGlyphCount(glyphCount)
1021         , fTextByteLength(0) {}
1022     // The clusters[] array is an array of offsets into utf8Text[],
1023     // one offset for each glyph.  See SkTextBlobBuilder for more info.
1024     Clusterator(const uint32_t* clusters,
1025                 const char* utf8Text,
1026                 uint32_t glyphCount,
1027                 uint32_t textByteLength)
1028         : fClusters(clusters)
1029         , fUtf8Text(utf8Text)
1030         , fGlyphCount(glyphCount)
1031         , fTextByteLength(textByteLength) {
1032         // This is a cheap heuristic for /ReversedChars which seems to
1033         // work for clusters produced by HarfBuzz, which either
1034         // increase from zero (LTR) or decrease to zero (RTL).
1035         // "ReversedChars" is how PDF deals with RTL text.
1036         fReversedChars =
1037             fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1038     }
1039     struct Cluster {
1040         const char* fUtf8Text;
1041         uint32_t fTextByteLength;
1042         uint32_t fGlyphIndex;
1043         uint32_t fGlyphCount;
1044         explicit operator bool() const { return fGlyphCount != 0; }
1045     };
1046     // True if this looks like right-to-left text.
1047     bool reversedChars() const { return fReversedChars; }
1048     Cluster next() {
1049         if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1050             // These glyphs have no text.  Treat as one "cluster".
1051             uint32_t glyphCount = fGlyphCount;
1052             fGlyphCount = 0;
1053             return Cluster{nullptr, 0, 0, glyphCount};
1054         }
1055         if (fGlyphCount == 0 || fTextByteLength == 0) {
1056             return Cluster{nullptr, 0, 0, 0};  // empty
1057         }
1058         SkASSERT(fUtf8Text);
1059         SkASSERT(fClusters);
1060         uint32_t cluster = fClusters[0];
1061         if (cluster >= fTextByteLength) {
1062             return Cluster{nullptr, 0, 0, 0};  // bad input.
1063         }
1064         uint32_t glyphsInCluster = 1;
1065         while (glyphsInCluster < fGlyphCount &&
1066                fClusters[glyphsInCluster] == cluster) {
1067             ++glyphsInCluster;
1068         }
1069         SkASSERT(glyphsInCluster <= fGlyphCount);
1070         uint32_t textLength = 0;
1071         if (glyphsInCluster == fGlyphCount) {
1072             // consumes rest of glyphs and rest of text
1073             if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1074                 textLength = fTextByteLength - cluster;
1075             } else { // RTL text; last cluster.
1076                 SkASSERT(fPreviousCluster < fTextByteLength);
1077                 if (fPreviousCluster <= cluster) {  // bad input.
1078                     return Cluster{nullptr, 0, 0, 0};
1079                 }
1080                 textLength = fPreviousCluster - cluster;
1081             }
1082             fGlyphCount = 0;
1083             return Cluster{fUtf8Text + cluster,
1084                            textLength,
1085                            fGlyphIndex,
1086                            glyphsInCluster};
1087         }
1088         SkASSERT(glyphsInCluster < fGlyphCount);
1089         uint32_t nextCluster = fClusters[glyphsInCluster];
1090         if (nextCluster >= fTextByteLength) {
1091             return Cluster{nullptr, 0, 0, 0};  // bad input.
1092         }
1093         if (nextCluster > cluster) { // LTR text
1094             if (kInvalidCluster != fPreviousCluster) {
1095                 return Cluster{nullptr, 0, 0, 0};  // bad input.
1096             }
1097             textLength = nextCluster - cluster;
1098         } else { // RTL text
1099             SkASSERT(nextCluster < cluster);
1100             if (kInvalidCluster == fPreviousCluster) { // first cluster
1101                 textLength = fTextByteLength - cluster;
1102             } else { // later cluster
1103                 if (fPreviousCluster <= cluster) {
1104                     return Cluster{nullptr, 0, 0, 0}; // bad input.
1105                 }
1106                 textLength = fPreviousCluster - cluster;
1107             }
1108             fPreviousCluster = cluster;
1109         }
1110         uint32_t glyphIndex = fGlyphIndex;
1111         fGlyphCount -= glyphsInCluster;
1112         fGlyphIndex += glyphsInCluster;
1113         fClusters   += glyphsInCluster;
1114         return Cluster{fUtf8Text + cluster,
1115                        textLength,
1116                        glyphIndex,
1117                        glyphsInCluster};
1118     }
1119
1120 private:
1121     static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1122     const uint32_t* fClusters;
1123     const char* fUtf8Text;
1124     uint32_t fGlyphCount;
1125     uint32_t fTextByteLength;
1126     uint32_t fGlyphIndex = 0;
1127     uint32_t fPreviousCluster = kInvalidCluster;
1128     bool fReversedChars = false;
1129 };
1130
1131 struct TextStorage {
1132     SkAutoTMalloc<char> fUtf8textStorage;
1133     SkAutoTMalloc<uint32_t> fClusterStorage;
1134     SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1135 };
1136 }  // namespace
1137
1138 /** Given some unicode text (as passed to drawText(), convert to
1139     glyphs (via primitive shaping), while preserving
1140     glyph-to-character mapping information. */
1141 static Clusterator make_clusterator(
1142         const void* sourceText,
1143         size_t sourceByteCount,
1144         const SkPaint& paint,
1145         TextStorage* storage,
1146         int glyphCount) {
1147     SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1148     SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1149     SkASSERT(glyphCount > 0);
1150     storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1151     (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1152     storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1153     uint32_t* clusters = storage->fClusterStorage.get();
1154     uint32_t utf8ByteCount = 0;
1155     const char* utf8Text = nullptr;
1156     switch (paint.getTextEncoding()) {
1157         case SkPaint::kUTF8_TextEncoding: {
1158             const char* txtPtr = (const char*)sourceText;
1159             for (int i = 0; i < glyphCount; ++i) {
1160                 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1161                 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1162                 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1163             }
1164             SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1165             utf8ByteCount = SkToU32(sourceByteCount);
1166             utf8Text = (const char*)sourceText;
1167             break;
1168         }
1169         case SkPaint::kUTF16_TextEncoding: {
1170             const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1171             int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1172             utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1173             storage->fUtf8textStorage.reset(utf8ByteCount);
1174             char* txtPtr = storage->fUtf8textStorage.get();
1175             utf8Text = txtPtr;
1176             int clusterIndex = 0;
1177             while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1178                 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1179                 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1180                 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1181             }
1182             SkASSERT(clusterIndex == glyphCount);
1183             SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1184             SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1185             break;
1186         }
1187         case SkPaint::kUTF32_TextEncoding: {
1188             const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1189             int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1190             SkASSERT(glyphCount == utf32count);
1191             for (int i = 0; i < utf32count; ++i) {
1192                 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1193             }
1194             storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1195             char* txtPtr = storage->fUtf8textStorage.get();
1196             utf8Text = txtPtr;
1197             for (int i = 0; i < utf32count; ++i) {
1198                 clusters[i] = SkToU32(txtPtr - utf8Text);
1199                 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1200             }
1201             break;
1202         }
1203         default:
1204             SkDEBUGFAIL("");
1205             break;
1206     }
1207     return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1208 }
1209
1210 static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1211     return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1212 }
1213
1214 static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1215     wStream->writeText("/");
1216     char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1217     wStream->write(&prefix, 1);
1218     wStream->writeDecAsText(fontIndex);
1219     wStream->writeText(" ");
1220     SkPDFUtils::AppendScalar(textSize, wStream);
1221     wStream->writeText(" Tf\n");
1222 }
1223
1224 void SkPDFDevice::internalDrawText(
1225         const SkDraw& d, const void* sourceText, size_t sourceByteCount,
1226         const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1227         SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1228         uint32_t textByteLength, const char* utf8Text) {
1229     NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1230     if (srcPaint.getMaskFilter() != nullptr) {
1231         // Don't pretend we support drawing MaskFilters, it makes for artifacts
1232         // making text unreadable (e.g. same text twice when using CSS shadows).
1233         return;
1234     }
1235     NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1236     if (srcPaint.isVerticalText()) {
1237         // Don't pretend we support drawing vertical text.  It is not
1238         // clear to me how to switch to "vertical writing" mode in PDF.
1239         // Currently neither Chromium or Android set this flag.
1240         // https://bug.skia.org/5665
1241         return;
1242     }
1243     if (0 == sourceByteCount || !sourceText) {
1244         return;
1245     }
1246     SkPaint paint = calculate_text_paint(srcPaint);
1247     replace_srcmode_on_opaque_paint(&paint);
1248     if (!paint.getTypeface()) {
1249         paint.setTypeface(SkTypeface::MakeDefault());
1250     }
1251     SkTypeface* typeface = paint.getTypeface();
1252     if (!typeface) {
1253         SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1254         return;
1255     }
1256
1257     const SkAdvancedTypefaceMetrics* metrics =
1258         SkPDFFont::GetMetrics(typeface, fDocument->canon());
1259     if (!metrics) {
1260         return;
1261     }
1262     int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1263     if (glyphCount <= 0) {
1264         return;
1265     }
1266
1267     // These three heap buffers are only used in the case where no glyphs
1268     // are passed to drawText() (most clients pass glyphs or a textblob).
1269     TextStorage storage;
1270     const SkGlyphID* glyphs = nullptr;
1271     Clusterator clusterator;
1272     if (textByteLength > 0) {
1273         SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1274         glyphs = (const SkGlyphID*)sourceText;
1275         clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1276         SkASSERT(clusters);
1277         SkASSERT(utf8Text);
1278         SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1279         SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1280     } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1281         SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1282         glyphs = (const SkGlyphID*)sourceText;
1283         clusterator = Clusterator(SkToU32(glyphCount));
1284         SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1285         SkASSERT(nullptr == clusters);
1286         SkASSERT(nullptr == utf8Text);
1287     } else {
1288         SkASSERT(nullptr == clusters);
1289         SkASSERT(nullptr == utf8Text);
1290         clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1291                                        &storage, glyphCount);
1292         glyphs = storage.fGlyphStorage;
1293     }
1294     bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
1295     paint.setHinting(SkPaint::kNo_Hinting);
1296     SkAutoGlyphCache glyphCache(paint, nullptr, nullptr);
1297
1298     SkPaint::Align alignment = paint.getTextAlign();
1299     float alignmentFactor = SkPaint::kLeft_Align   == alignment ?  0.0f :
1300                             SkPaint::kCenter_Align == alignment ? -0.5f :
1301                             /* SkPaint::kRight_Align */           -1.0f;
1302     if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
1303         SkScalar advance = 0;
1304         for (int i = 0; i < glyphCount; ++i) {
1305             advance += glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
1306         }
1307         offset.offset(alignmentFactor * advance, 0);
1308     }
1309     ScopedContentEntry content(this, d, paint, true);
1310     if (!content.entry()) {
1311         return;
1312     }
1313     SkDynamicMemoryWStream* out = &content.entry()->fContent;
1314     SkScalar textSize = paint.getTextSize();
1315     const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
1316
1317     out->writeText("BT\n");
1318     SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1319
1320     const SkGlyphID maxGlyphID = metrics->fLastGlyphID;
1321     bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1322     if (clusterator.reversedChars()) {
1323         out->writeText("/ReversedChars BMC\n");
1324     }
1325     SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1326     GlyphPositioner glyphPositioner(out,
1327                                     paint.getTextSkewX(),
1328                                     multiByteGlyphs,
1329                                     defaultPositioning,
1330                                     offset);
1331     SkPDFFont* font = nullptr;
1332
1333     while (Clusterator::Cluster c = clusterator.next()) {
1334         int index = c.fGlyphIndex;
1335         int glyphLimit = index + c.fGlyphCount;
1336
1337         bool actualText = false;
1338         SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1339         if (c.fUtf8Text) {  // real cluster
1340             // Check if `/ActualText` needed.
1341             const char* textPtr = c.fUtf8Text;
1342             // TODO(halcanary): validate utf8 input.
1343             SkUnichar unichar = SkUTF8_NextUnichar(&textPtr);
1344             const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1345             if (textPtr < textEnd ||                                  // more characters left
1346                 glyphLimit > index + 1 ||                             // toUnicode wouldn't work
1347                 unichar != map_glyph(glyphToUnicode, glyphs[index]))  // test single Unichar map
1348             {
1349                 glyphPositioner.flush();
1350                 out->writeText("/Span<</ActualText <");
1351                 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF);  // U+FEFF = BYTE ORDER MARK
1352                 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1353                 SkPDFUtils::WriteUTF16beHex(out, unichar);  // first char
1354                 while (textPtr < textEnd) {
1355                     unichar = SkUTF8_NextUnichar(&textPtr);
1356                     SkPDFUtils::WriteUTF16beHex(out, unichar);
1357                 }
1358                 out->writeText("> >> BDC\n");  // begin marked-content sequence
1359                                                // with an associated property list.
1360                 actualText = true;
1361             }
1362         }
1363         for (; index < glyphLimit; ++index) {
1364             SkGlyphID gid = glyphs[index];
1365             if (gid > maxGlyphID) {
1366                 continue;
1367             }
1368             if (!font || !font->hasGlyph(gid)) {
1369                 // Not yet specified font or need to switch font.
1370                 int fontIndex = this->getFontResourceIndex(typeface, gid);
1371                 // All preconditions for SkPDFFont::GetFontResource are met.
1372                 SkASSERT(fontIndex >= 0);
1373                 if (fontIndex < 0) {
1374                     return;
1375                 }
1376                 glyphPositioner.flush();
1377                 update_font(out, fontIndex, textSize);
1378                 font = fFontResources[fontIndex];
1379                 SkASSERT(font);  // All preconditions for SkPDFFont::GetFontResource are met.
1380                 if (!font) {
1381                     return;
1382                 }
1383                 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1384             }
1385             SkPoint xy{0, 0};
1386             SkScalar advance{0};
1387             if (!defaultPositioning) {
1388                 advance = glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1389                 xy = SkTextBlob::kFull_Positioning == positioning
1390                    ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1391                    : SkPoint{pos[index], 0};
1392                 if (alignment != SkPaint::kLeft_Align) {
1393                     xy.offset(alignmentFactor * advance, 0);
1394                 }
1395             }
1396             font->noteGlyphUsage(gid);
1397             SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1398             glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1399         }
1400     }
1401 }
1402
1403 void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1404                            SkScalar x, SkScalar y, const SkPaint& paint) {
1405     this->internalDrawText(d, text, len, nullptr, SkTextBlob::kDefault_Positioning,
1406                            SkPoint{x, y}, paint, nullptr, 0, nullptr);
1407 }
1408
1409 void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1410                               const SkScalar pos[], int scalarsPerPos,
1411                               const SkPoint& offset, const SkPaint& paint) {
1412     this->internalDrawText(d, text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
1413                            offset, paint, nullptr, 0, nullptr);
1414 }
1415
1416 void SkPDFDevice::drawTextBlob(const SkDraw& draw, const SkTextBlob* blob, SkScalar x, SkScalar y,
1417                                const SkPaint &paint, SkDrawFilter* drawFilter) {
1418     for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1419         SkPaint runPaint(paint);
1420         it.applyFontToPaint(&runPaint);
1421         if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1422             continue;
1423         }
1424         runPaint.setFlags(this->filterTextFlags(runPaint));
1425         SkPoint offset = it.offset() + SkPoint{x, y};
1426         this->internalDrawText(draw, it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
1427                                it.pos(), it.positioning(), offset, runPaint,
1428                                it.clusters(), it.textSize(), it.text());
1429     }
1430 }
1431
1432 void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
1433                                int vertexCount, const SkPoint verts[],
1434                                const SkPoint texs[], const SkColor colors[],
1435                                SkBlendMode, const uint16_t indices[],
1436                                int indexCount, const SkPaint& paint) {
1437     if (d.fRC->isEmpty()) {
1438         return;
1439     }
1440     // TODO: implement drawVertices
1441 }
1442
1443 void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1444                              int x, int y, const SkPaint& paint) {
1445     SkASSERT(!paint.getImageFilter());
1446
1447     // Check if the source device is really a bitmapdevice (because that's what we returned
1448     // from createDevice (likely due to an imagefilter)
1449     SkPixmap pmap;
1450     if (device->peekPixels(&pmap)) {
1451         SkBitmap bitmap;
1452         bitmap.installPixels(pmap);
1453         this->drawSprite(d, bitmap, x, y, paint);
1454         return;
1455     }
1456
1457     // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
1458     SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
1459
1460     SkScalar scalarX = SkIntToScalar(x);
1461     SkScalar scalarY = SkIntToScalar(y);
1462     for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1463         SkRect r = l.rect.makeOffset(scalarX, scalarY);
1464         fLinkToURLs.emplace_back(r, l.data.get());
1465     }
1466     for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1467         SkRect r = l.rect.makeOffset(scalarX, scalarY);
1468         fLinkToDestinations.emplace_back(r, l.data.get());
1469     }
1470     for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1471         SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
1472         fNamedDestinations.emplace_back(d.nameData.get(), p);
1473     }
1474
1475     if (pdfDevice->isContentEmpty()) {
1476         return;
1477     }
1478
1479     SkMatrix matrix;
1480     matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1481     ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
1482     if (!content.entry()) {
1483         return;
1484     }
1485     if (content.needShape()) {
1486         SkPath shape;
1487         shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
1488                                        SkIntToScalar(device->width()),
1489                                        SkIntToScalar(device->height())));
1490         content.setShape(shape);
1491     }
1492     if (!content.needSource()) {
1493         return;
1494     }
1495
1496     sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
1497     SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
1498                                 &content.entry()->fContent);
1499 }
1500
1501 sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1502     return SkSurface::MakeRaster(info, &props);
1503 }
1504
1505
1506 sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
1507     SkTDArray<SkPDFObject*> fonts;
1508     fonts.setReserve(fFontResources.count());
1509     for (SkPDFFont* font : fFontResources) {
1510         fonts.push(font);
1511     }
1512     return SkPDFResourceDict::Make(
1513             &fGraphicStateResources,
1514             &fShaderResources,
1515             &fXObjectResources,
1516             &fonts);
1517 }
1518
1519 sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
1520     auto mediaBox = sk_make_sp<SkPDFArray>();
1521     mediaBox->reserve(4);
1522     mediaBox->appendInt(0);
1523     mediaBox->appendInt(0);
1524     mediaBox->appendInt(fPageSize.width());
1525     mediaBox->appendInt(fPageSize.height());
1526     return mediaBox;
1527 }
1528
1529 std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
1530     SkDynamicMemoryWStream buffer;
1531     if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1532         SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
1533     }
1534
1535     GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, &buffer);
1536     for (const auto& entry : fContentEntries) {
1537         SkPoint translation;
1538         translation.iset(this->getOrigin());
1539         translation.negate();
1540         gsState.updateClip(entry.fState.fClipStack, entry.fState.fClipRegion,
1541                            translation);
1542         gsState.updateMatrix(entry.fState.fMatrix);
1543         gsState.updateDrawingState(entry.fState);
1544
1545         entry.fContent.writeToStream(&buffer);
1546     }
1547     gsState.drainStack();
1548     if (buffer.bytesWritten() > 0) {
1549         return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1550     } else {
1551         return skstd::make_unique<SkMemoryStream>();
1552     }
1553 }
1554
1555 /* Draws an inverse filled path by using Path Ops to compute the positive
1556  * inverse using the current clip as the inverse bounds.
1557  * Return true if this was an inverse path and was properly handled,
1558  * otherwise returns false and the normal drawing routine should continue,
1559  * either as a (incorrect) fallback or because the path was not inverse
1560  * in the first place.
1561  */
1562 bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
1563                                     const SkPaint& paint, bool pathIsMutable,
1564                                     const SkMatrix* prePathMatrix) {
1565     if (!origPath.isInverseFillType()) {
1566         return false;
1567     }
1568
1569     if (d.fRC->isEmpty()) {
1570         return false;
1571     }
1572
1573     SkPath modifiedPath;
1574     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1575     SkPaint noInversePaint(paint);
1576
1577     // Merge stroking operations into final path.
1578     if (SkPaint::kStroke_Style == paint.getStyle() ||
1579         SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1580         bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1581         if (doFillPath) {
1582             noInversePaint.setStyle(SkPaint::kFill_Style);
1583             noInversePaint.setStrokeWidth(0);
1584             pathPtr = &modifiedPath;
1585         } else {
1586             // To be consistent with the raster output, hairline strokes
1587             // are rendered as non-inverted.
1588             modifiedPath.toggleInverseFillType();
1589             drawPath(d, modifiedPath, paint, nullptr, true);
1590             return true;
1591         }
1592     }
1593
1594     // Get bounds of clip in current transform space
1595     // (clip bounds are given in device space).
1596     SkRect bounds;
1597     SkMatrix transformInverse;
1598     SkMatrix totalMatrix = *d.fMatrix;
1599     if (prePathMatrix) {
1600         totalMatrix.preConcat(*prePathMatrix);
1601     }
1602     if (!totalMatrix.invert(&transformInverse)) {
1603         return false;
1604     }
1605     bounds.set(d.fRC->getBounds());
1606     transformInverse.mapRect(&bounds);
1607
1608     // Extend the bounds by the line width (plus some padding)
1609     // so the edge doesn't cause a visible stroke.
1610     bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1611                   paint.getStrokeWidth() + SK_Scalar1);
1612
1613     if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1614         return false;
1615     }
1616
1617     drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
1618     return true;
1619 }
1620
1621 void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
1622                                         const SkMatrix& matrix,
1623                                         const char key[], SkData* value) {
1624     if (!value) {
1625         return;
1626     }
1627
1628     if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1629         SkPoint transformedPoint;
1630         matrix.mapXY(point.x(), point.y(), &transformedPoint);
1631         fNamedDestinations.emplace_back(value, transformedPoint);
1632     }
1633 }
1634
1635 void SkPDFDevice::handlePathAnnotation(const SkPath& path,
1636                                        const SkDraw& d,
1637                                        const char key[], SkData* value) {
1638     if (!value) {
1639         return;
1640     }
1641
1642     SkRasterClip clip = *d.fRC;
1643     clip.op(path, *d.fMatrix, SkIRect::MakeWH(width(), height()),
1644             SkRegion::kIntersect_Op,
1645             false);
1646     SkRect transformedRect = SkRect::Make(clip.getBounds());
1647
1648     if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
1649         if (!transformedRect.isEmpty()) {
1650             fLinkToURLs.emplace_back(transformedRect, value);
1651         }
1652     } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
1653         if (!transformedRect.isEmpty()) {
1654             fLinkToDestinations.emplace_back(transformedRect, value);
1655         }
1656     }
1657 }
1658
1659 void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1660     array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
1661     for (const RectWithData& rectWithURL : fLinkToURLs) {
1662         SkRect r;
1663         fInitialTransform.mapRect(&r, rectWithURL.rect);
1664         array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
1665     }
1666     for (const RectWithData& linkToDestination : fLinkToDestinations) {
1667         SkRect r;
1668         fInitialTransform.mapRect(&r, linkToDestination.rect);
1669         array->appendObject(
1670                 create_link_named_dest(linkToDestination.data.get(), r));
1671     }
1672 }
1673
1674 void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
1675     for (const NamedDestination& dest : fNamedDestinations) {
1676         auto pdfDest = sk_make_sp<SkPDFArray>();
1677         pdfDest->reserve(5);
1678         pdfDest->appendObjRef(sk_ref_sp(page));
1679         pdfDest->appendName("XYZ");
1680         SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
1681         pdfDest->appendScalar(p.x());
1682         pdfDest->appendScalar(p.y());
1683         pdfDest->appendInt(0);  // Leave zoom unchanged
1684         SkString name(static_cast<const char*>(dest.nameData->data()));
1685         dict->insertObject(name, std::move(pdfDest));
1686     }
1687 }
1688
1689 sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
1690     SkMatrix inverseTransform = SkMatrix::I();
1691     if (!fInitialTransform.isIdentity()) {
1692         if (!fInitialTransform.invert(&inverseTransform)) {
1693             SkDEBUGFAIL("Layer initial transform should be invertible.");
1694             inverseTransform.reset();
1695         }
1696     }
1697     sk_sp<SkPDFObject> xobject =
1698         SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
1699                              this->makeResourceDict(), inverseTransform, nullptr);
1700     // We always draw the form xobjects that we create back into the device, so
1701     // we simply preserve the font usage instead of pulling it out and merging
1702     // it back in later.
1703     this->cleanUp();  // Reset this device to have no content.
1704     this->init();
1705     return xobject;
1706 }
1707
1708 void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1709                                           sk_sp<SkPDFObject> mask,
1710                                           const SkClipStack* clipStack,
1711                                           const SkRegion& clipRegion,
1712                                           SkBlendMode mode,
1713                                           bool invertClip) {
1714     if (clipRegion.isEmpty() && !invertClip) {
1715         return;
1716     }
1717
1718     sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
1719             std::move(mask), invertClip,
1720             SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
1721
1722     SkMatrix identity;
1723     identity.reset();
1724     SkPaint paint;
1725     paint.setBlendMode(mode);
1726     ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
1727     if (!content.entry()) {
1728         return;
1729     }
1730     SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1731                                   &content.entry()->fContent);
1732     SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
1733
1734     // Call makeNoSmaskGraphicState() instead of
1735     // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1736     // can deduplicate.
1737     sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
1738     SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1739                                   &content.entry()->fContent);
1740 }
1741
1742 SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1743                                              const SkRegion& clipRegion,
1744                                              const SkMatrix& matrix,
1745                                              const SkPaint& paint,
1746                                              bool hasText,
1747                                              sk_sp<SkPDFObject>* dst) {
1748     *dst = nullptr;
1749     if (clipRegion.isEmpty()) {
1750         return nullptr;
1751     }
1752
1753     // The clip stack can come from an SkDraw where it is technically optional.
1754     SkClipStack synthesizedClipStack;
1755     if (clipStack == nullptr) {
1756         if (clipRegion == fExistingClipRegion) {
1757             clipStack = &fExistingClipStack;
1758         } else {
1759             // GraphicStackState::updateClip expects the clip stack to have
1760             // fExistingClip as a prefix, so start there, then set the clip
1761             // to the passed region.
1762             synthesizedClipStack = fExistingClipStack;
1763             SkPath clipPath;
1764             clipRegion.getBoundaryPath(&clipPath);
1765             synthesizedClipStack.clipPath(clipPath, SkMatrix::I(), kReplace_SkClipOp, false);
1766             clipStack = &synthesizedClipStack;
1767         }
1768     }
1769
1770     SkBlendMode blendMode = paint.getBlendMode();
1771
1772     // For the following modes, we want to handle source and destination
1773     // separately, so make an object of what's already there.
1774     if (blendMode == SkBlendMode::kClear       ||
1775             blendMode == SkBlendMode::kSrc     ||
1776             blendMode == SkBlendMode::kSrcIn   ||
1777             blendMode == SkBlendMode::kDstIn   ||
1778             blendMode == SkBlendMode::kSrcOut  ||
1779             blendMode == SkBlendMode::kDstOut  ||
1780             blendMode == SkBlendMode::kSrcATop ||
1781             blendMode == SkBlendMode::kDstATop ||
1782             blendMode == SkBlendMode::kModulate) {
1783         if (!isContentEmpty()) {
1784             *dst = this->makeFormXObjectFromDevice();
1785             SkASSERT(isContentEmpty());
1786         } else if (blendMode != SkBlendMode::kSrc &&
1787                    blendMode != SkBlendMode::kSrcOut) {
1788             // Except for Src and SrcOut, if there isn't anything already there,
1789             // then we're done.
1790             return nullptr;
1791         }
1792     }
1793     // TODO(vandebo): Figure out how/if we can handle the following modes:
1794     // Xor, Plus.
1795
1796     // Dst xfer mode doesn't draw source at all.
1797     if (blendMode == SkBlendMode::kDst) {
1798         return nullptr;
1799     }
1800
1801     SkPDFDevice::ContentEntry* entry;
1802     if (fContentEntries.back() && fContentEntries.back()->fContent.getOffset() == 0) {
1803         entry = fContentEntries.back();
1804     } else if (blendMode != SkBlendMode::kDstOver) {
1805         entry = fContentEntries.emplace_back();
1806     } else {
1807         entry = fContentEntries.emplace_front();
1808     }
1809     populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
1810                                        hasText, &entry->fState);
1811     return entry;
1812 }
1813
1814 void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
1815                                      sk_sp<SkPDFObject> dst,
1816                                      SkPath* shape) {
1817     if (blendMode != SkBlendMode::kClear       &&
1818             blendMode != SkBlendMode::kSrc     &&
1819             blendMode != SkBlendMode::kDstOver &&
1820             blendMode != SkBlendMode::kSrcIn   &&
1821             blendMode != SkBlendMode::kDstIn   &&
1822             blendMode != SkBlendMode::kSrcOut  &&
1823             blendMode != SkBlendMode::kDstOut  &&
1824             blendMode != SkBlendMode::kSrcATop &&
1825             blendMode != SkBlendMode::kDstATop &&
1826             blendMode != SkBlendMode::kModulate) {
1827         SkASSERT(!dst);
1828         return;
1829     }
1830     if (blendMode == SkBlendMode::kDstOver) {
1831         SkASSERT(!dst);
1832         if (fContentEntries.front()->fContent.getOffset() == 0) {
1833             // For DstOver, an empty content entry was inserted before the rest
1834             // of the content entries. If nothing was drawn, it needs to be
1835             // removed.
1836             fContentEntries.pop_front();
1837         }
1838         return;
1839     }
1840     if (!dst) {
1841         SkASSERT(blendMode == SkBlendMode::kSrc ||
1842                  blendMode == SkBlendMode::kSrcOut);
1843         return;
1844     }
1845
1846     SkASSERT(dst);
1847     SkASSERT(fContentEntries.count() == 1);
1848     // Changing the current content into a form-xobject will destroy the clip
1849     // objects which is fine since the xobject will already be clipped. However
1850     // if source has shape, we need to clip it too, so a copy of the clip is
1851     // saved.
1852
1853     SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
1854     SkRegion clipRegion = fContentEntries.front()->fState.fClipRegion;
1855
1856     SkMatrix identity;
1857     identity.reset();
1858     SkPaint stockPaint;
1859
1860     sk_sp<SkPDFObject> srcFormXObject;
1861     if (isContentEmpty()) {
1862         // If nothing was drawn and there's no shape, then the draw was a
1863         // no-op, but dst needs to be restored for that to be true.
1864         // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1865         // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1866         // reduces to Dst.
1867         if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1868                 blendMode == SkBlendMode::kSrcATop) {
1869             ScopedContentEntry content(this, &fExistingClipStack,
1870                                        fExistingClipRegion, identity,
1871                                        stockPaint);
1872             // TODO: addXObjectResource take sk_sp
1873             SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
1874                                         &content.entry()->fContent);
1875             return;
1876         } else {
1877             blendMode = SkBlendMode::kClear;
1878         }
1879     } else {
1880         SkASSERT(fContentEntries.count() == 1);
1881         srcFormXObject = this->makeFormXObjectFromDevice();
1882     }
1883
1884     // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1885     // without alpha.
1886     if (blendMode == SkBlendMode::kSrcATop) {
1887         // TODO(vandebo): In order to properly support SrcATop we have to track
1888         // the shape of what's been drawn at all times. It's the intersection of
1889         // the non-transparent parts of the device and the outlines (shape) of
1890         // all images and devices drawn.
1891         drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1892                                 &fExistingClipStack, fExistingClipRegion,
1893                                 SkBlendMode::kSrcOver, true);
1894     } else {
1895         if (shape != nullptr) {
1896             // Draw shape into a form-xobject.
1897             SkRasterClip rc(clipRegion);
1898             SkDraw d;
1899             d.fMatrix = &identity;
1900             d.fRC = &rc;
1901             d.fClipStack = &clipStack;
1902             SkPaint filledPaint;
1903             filledPaint.setColor(SK_ColorBLACK);
1904             filledPaint.setStyle(SkPaint::kFill_Style);
1905             this->drawPath(d, *shape, filledPaint, nullptr, true);
1906             drawFormXObjectWithMask(addXObjectResource(dst.get()),
1907                                     this->makeFormXObjectFromDevice(),
1908                                     &fExistingClipStack, fExistingClipRegion,
1909                                     SkBlendMode::kSrcOver, true);
1910
1911         } else {
1912             drawFormXObjectWithMask(addXObjectResource(dst.get()), srcFormXObject,
1913                                     &fExistingClipStack, fExistingClipRegion,
1914                                     SkBlendMode::kSrcOver, true);
1915         }
1916     }
1917
1918     if (blendMode == SkBlendMode::kClear) {
1919         return;
1920     } else if (blendMode == SkBlendMode::kSrc ||
1921             blendMode == SkBlendMode::kDstATop) {
1922         ScopedContentEntry content(this, &fExistingClipStack,
1923                                    fExistingClipRegion, identity, stockPaint);
1924         if (content.entry()) {
1925             SkPDFUtils::DrawFormXObject(
1926                     this->addXObjectResource(srcFormXObject.get()),
1927                     &content.entry()->fContent);
1928         }
1929         if (blendMode == SkBlendMode::kSrc) {
1930             return;
1931         }
1932     } else if (blendMode == SkBlendMode::kSrcATop) {
1933         ScopedContentEntry content(this, &fExistingClipStack,
1934                                    fExistingClipRegion, identity, stockPaint);
1935         if (content.entry()) {
1936             SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
1937                                         &content.entry()->fContent);
1938         }
1939     }
1940
1941     SkASSERT(blendMode == SkBlendMode::kSrcIn   ||
1942              blendMode == SkBlendMode::kDstIn   ||
1943              blendMode == SkBlendMode::kSrcOut  ||
1944              blendMode == SkBlendMode::kDstOut  ||
1945              blendMode == SkBlendMode::kSrcATop ||
1946              blendMode == SkBlendMode::kDstATop ||
1947              blendMode == SkBlendMode::kModulate);
1948
1949     if (blendMode == SkBlendMode::kSrcIn ||
1950             blendMode == SkBlendMode::kSrcOut ||
1951             blendMode == SkBlendMode::kSrcATop) {
1952         drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1953                                 std::move(dst),
1954                                 &fExistingClipStack, fExistingClipRegion,
1955                                 SkBlendMode::kSrcOver,
1956                                 blendMode == SkBlendMode::kSrcOut);
1957         return;
1958     } else {
1959         SkBlendMode mode = SkBlendMode::kSrcOver;
1960         int resourceID = addXObjectResource(dst.get());
1961         if (blendMode == SkBlendMode::kModulate) {
1962             drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1963                                     std::move(dst), &fExistingClipStack,
1964                                     fExistingClipRegion,
1965                                     SkBlendMode::kSrcOver, false);
1966             mode = SkBlendMode::kMultiply;
1967         }
1968         drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
1969                                 &fExistingClipStack, fExistingClipRegion, mode,
1970                                 blendMode == SkBlendMode::kDstOut);
1971         return;
1972     }
1973 }
1974
1975 bool SkPDFDevice::isContentEmpty() {
1976     if (!fContentEntries.front() || fContentEntries.front()->fContent.getOffset() == 0) {
1977         SkASSERT(fContentEntries.count() <= 1);
1978         return true;
1979     }
1980     return false;
1981 }
1982
1983 void SkPDFDevice::populateGraphicStateEntryFromPaint(
1984         const SkMatrix& matrix,
1985         const SkClipStack& clipStack,
1986         const SkRegion& clipRegion,
1987         const SkPaint& paint,
1988         bool hasText,
1989         SkPDFDevice::GraphicStateEntry* entry) {
1990     NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1991     NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1992     NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
1993
1994     entry->fMatrix = matrix;
1995     entry->fClipStack = clipStack;
1996     entry->fClipRegion = clipRegion;
1997     entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1998     entry->fShaderIndex = -1;
1999
2000     // PDF treats a shader as a color, so we only set one or the other.
2001     sk_sp<SkPDFObject> pdfShader;
2002     SkShader* shader = paint.getShader();
2003     SkColor color = paint.getColor();
2004     if (shader) {
2005         // PDF positions patterns relative to the initial transform, so
2006         // we need to apply the current transform to the shader parameters.
2007         SkMatrix transform = matrix;
2008         transform.postConcat(fInitialTransform);
2009
2010         // PDF doesn't support kClamp_TileMode, so we simulate it by making
2011         // a pattern the size of the current clip.
2012         SkIRect bounds = clipRegion.getBounds();
2013
2014         // We need to apply the initial transform to bounds in order to get
2015         // bounds in a consistent coordinate system.
2016         SkRect boundsTemp;
2017         boundsTemp.set(bounds);
2018         fInitialTransform.mapRect(&boundsTemp);
2019         boundsTemp.roundOut(&bounds);
2020
2021         SkScalar rasterScale =
2022                 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2023         pdfShader = SkPDFShader::GetPDFShader(
2024                 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
2025
2026         if (pdfShader.get()) {
2027             // pdfShader has been canonicalized so we can directly compare
2028             // pointers.
2029             int resourceIndex = fShaderResources.find(pdfShader.get());
2030             if (resourceIndex < 0) {
2031                 resourceIndex = fShaderResources.count();
2032                 fShaderResources.push(pdfShader.get());
2033                 pdfShader.get()->ref();
2034             }
2035             entry->fShaderIndex = resourceIndex;
2036         } else {
2037             // A color shader is treated as an invalid shader so we don't have
2038             // to set a shader just for a color.
2039             SkShader::GradientInfo gradientInfo;
2040             SkColor gradientColor;
2041             gradientInfo.fColors = &gradientColor;
2042             gradientInfo.fColorOffsets = nullptr;
2043             gradientInfo.fColorCount = 1;
2044             if (shader->asAGradient(&gradientInfo) ==
2045                     SkShader::kColor_GradientType) {
2046                 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2047                 color = gradientColor;
2048             }
2049         }
2050     }
2051
2052     sk_sp<SkPDFGraphicState> newGraphicState;
2053     if (color == paint.getColor()) {
2054         newGraphicState.reset(
2055                 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
2056     } else {
2057         SkPaint newPaint = paint;
2058         newPaint.setColor(color);
2059         newGraphicState.reset(
2060                 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
2061     }
2062     int resourceIndex = addGraphicStateResource(newGraphicState.get());
2063     entry->fGraphicStateIndex = resourceIndex;
2064
2065     if (hasText) {
2066         entry->fTextScaleX = paint.getTextScaleX();
2067         entry->fTextFill = paint.getStyle();
2068     } else {
2069         entry->fTextScaleX = 0;
2070     }
2071 }
2072
2073 int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
2074     // Assumes that gs has been canonicalized (so we can directly compare
2075     // pointers).
2076     int result = fGraphicStateResources.find(gs);
2077     if (result < 0) {
2078         result = fGraphicStateResources.count();
2079         fGraphicStateResources.push(gs);
2080         gs->ref();
2081     }
2082     return result;
2083 }
2084
2085 int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2086     // TODO(halcanary): make this take a sk_sp<SkPDFObject>
2087     // Assumes that xobject has been canonicalized (so we can directly compare
2088     // pointers).
2089     int result = fXObjectResources.find(xObject);
2090     if (result < 0) {
2091         result = fXObjectResources.count();
2092         fXObjectResources.push(SkRef(xObject));
2093     }
2094     return result;
2095 }
2096
2097 int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
2098     sk_sp<SkPDFFont> newFont(
2099             SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
2100     if (!newFont) {
2101         return -1;
2102     }
2103     int resourceIndex = fFontResources.find(newFont.get());
2104     if (resourceIndex < 0) {
2105         fDocument->registerFont(newFont.get());
2106         resourceIndex = fFontResources.count();
2107         fFontResources.push(newFont.release());
2108     }
2109     return resourceIndex;
2110 }
2111
2112 static SkSize rect_to_size(const SkRect& r) {
2113     return SkSize::Make(r.width(), r.height());
2114 }
2115
2116 static sk_sp<SkImage> color_filter(const SkImageSubset& imageSubset,
2117                                    SkColorFilter* colorFilter) {
2118     auto surface =
2119         SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.dimensions()));
2120     SkASSERT(surface);
2121     SkCanvas* canvas = surface->getCanvas();
2122     canvas->clear(SK_ColorTRANSPARENT);
2123     SkPaint paint;
2124     paint.setColorFilter(sk_ref_sp(colorFilter));
2125     imageSubset.draw(canvas, &paint);
2126     canvas->flush();
2127     return surface->makeImageSnapshot();
2128 }
2129
2130 ////////////////////////////////////////////////////////////////////////////////
2131 void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2132                                     const SkClipStack* clipStack,
2133                                     const SkRegion& origClipRegion,
2134                                     SkImageSubset imageSubset,
2135                                     const SkPaint& paint) {
2136     if (imageSubset.dimensions().isZero()) {
2137         return;
2138     }
2139     #ifdef SK_PDF_IMAGE_STATS
2140     gDrawImageCalls.fetch_add(1);
2141     #endif
2142     SkMatrix matrix = origMatrix;
2143     SkRegion perspectiveBounds;
2144     const SkRegion* clipRegion = &origClipRegion;
2145
2146     // Rasterize the bitmap using perspective in a new bitmap.
2147     if (origMatrix.hasPerspective()) {
2148         if (fRasterDpi == 0) {
2149             return;
2150         }
2151         // Transform the bitmap in the new space, without taking into
2152         // account the initial transform.
2153         SkPath perspectiveOutline;
2154         SkRect imageBounds = SkRect::Make(imageSubset.bounds());
2155         perspectiveOutline.addRect(imageBounds);
2156         perspectiveOutline.transform(origMatrix);
2157
2158         // TODO(edisonn): perf - use current clip too.
2159         // Retrieve the bounds of the new shape.
2160         SkRect bounds = perspectiveOutline.getBounds();
2161
2162         // Transform the bitmap in the new space, taking into
2163         // account the initial transform.
2164         SkMatrix total = origMatrix;
2165         total.postConcat(fInitialTransform);
2166         SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2167                             SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2168         total.postScale(dpiScale, dpiScale);
2169
2170         SkPath physicalPerspectiveOutline;
2171         physicalPerspectiveOutline.addRect(imageBounds);
2172         physicalPerspectiveOutline.transform(total);
2173
2174         SkRect physicalPerspectiveBounds =
2175                 physicalPerspectiveOutline.getBounds();
2176         SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2177         SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
2178
2179         // TODO(edisonn): A better approach would be to use a bitmap shader
2180         // (in clamp mode) and draw a rect over the entire bounding box. Then
2181         // intersect perspectiveOutline to the clip. That will avoid introducing
2182         // alpha to the image while still giving good behavior at the edge of
2183         // the image.  Avoiding alpha will reduce the pdf size and generation
2184         // CPU time some.
2185
2186         SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2187
2188         auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
2189         if (!surface) {
2190             return;
2191         }
2192         SkCanvas* canvas = surface->getCanvas();
2193         canvas->clear(SK_ColorTRANSPARENT);
2194
2195         SkScalar deltaX = bounds.left();
2196         SkScalar deltaY = bounds.top();
2197
2198         SkMatrix offsetMatrix = origMatrix;
2199         offsetMatrix.postTranslate(-deltaX, -deltaY);
2200         offsetMatrix.postScale(scaleX, scaleY);
2201
2202         // Translate the draw in the new canvas, so we perfectly fit the
2203         // shape in the bitmap.
2204         canvas->setMatrix(offsetMatrix);
2205         imageSubset.draw(canvas, nullptr);
2206         // Make sure the final bits are in the bitmap.
2207         canvas->flush();
2208
2209         // In the new space, we use the identity matrix translated
2210         // and scaled to reflect DPI.
2211         matrix.setScale(1 / scaleX, 1 / scaleY);
2212         matrix.postTranslate(deltaX, deltaY);
2213
2214         perspectiveBounds.setRect(bounds.roundOut());
2215         clipRegion = &perspectiveBounds;
2216
2217         imageSubset = SkImageSubset(surface->makeImageSnapshot());
2218     }
2219
2220     SkMatrix scaled;
2221     // Adjust for origin flip.
2222     scaled.setScale(SK_Scalar1, -SK_Scalar1);
2223     scaled.postTranslate(0, SK_Scalar1);
2224     // Scale the image up from 1x1 to WxH.
2225     SkIRect subset = imageSubset.bounds();
2226     scaled.postScale(SkIntToScalar(imageSubset.dimensions().width()),
2227                      SkIntToScalar(imageSubset.dimensions().height()));
2228     scaled.postConcat(matrix);
2229     ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
2230     if (!content.entry()) {
2231         return;
2232     }
2233     if (content.needShape()) {
2234         SkPath shape;
2235         shape.addRect(SkRect::Make(subset));
2236         shape.transform(matrix);
2237         content.setShape(shape);
2238     }
2239     if (!content.needSource()) {
2240         return;
2241     }
2242
2243     if (SkColorFilter* colorFilter = paint.getColorFilter()) {
2244         // TODO(https://bug.skia.org/4378): implement colorfilter on other
2245         // draw calls.  This code here works for all
2246         // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2247         // rasterize a layer on this backend).  Fortuanely, this seems
2248         // to be how Chromium impements most color-filters.
2249         sk_sp<SkImage> img = color_filter(imageSubset, colorFilter);
2250         imageSubset = SkImageSubset(std::move(img));
2251         // TODO(halcanary): de-dupe this by caching filtered images.
2252         // (maybe in the resource cache?)
2253     }
2254
2255     SkBitmapKey key = imageSubset.getKey();
2256     sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
2257     if (!pdfimage) {
2258         sk_sp<SkImage> img = imageSubset.makeImage();
2259         if (!img) {
2260             return;
2261         }
2262         pdfimage = SkPDFCreateBitmapObject(
2263                 std::move(img), fDocument->canon()->getPixelSerializer());
2264         if (!pdfimage) {
2265             return;
2266         }
2267         fDocument->serialize(pdfimage);  // serialize images early.
2268         fDocument->canon()->addPDFBitmap(key, pdfimage);
2269     }
2270     // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
2271     SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
2272                                 &content.entry()->fContent);
2273 }
2274
2275 ///////////////////////////////////////////////////////////////////////////////////////////////////
2276
2277 #include "SkSpecialImage.h"
2278 #include "SkImageFilter.h"
2279
2280 void SkPDFDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
2281                                  const SkPaint& paint) {
2282     SkASSERT(!srcImg->isTextureBacked());
2283
2284     SkBitmap resultBM;
2285
2286     SkImageFilter* filter = paint.getImageFilter();
2287     if (filter) {
2288         SkIPoint offset = SkIPoint::Make(0, 0);
2289         SkMatrix matrix = *draw.fMatrix;
2290         matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
2291         const SkIRect clipBounds = draw.fRC->getBounds().makeOffset(-x, -y);
2292         sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
2293         // TODO: Should PDF be operating in a specified color space? For now, run the filter
2294         // in the same color space as the source (this is different from all other backends).
2295         SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2296         SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
2297
2298         sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2299         if (resultImg) {
2300             SkPaint tmpUnfiltered(paint);
2301             tmpUnfiltered.setImageFilter(nullptr);
2302             if (resultImg->getROPixels(&resultBM)) {
2303                 this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2304             }
2305         }
2306     } else {
2307         if (srcImg->getROPixels(&resultBM)) {
2308             this->drawSprite(draw, resultBM, x, y, paint);
2309         }
2310     }
2311 }
2312
2313 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2314     return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2315 }
2316
2317 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
2318     // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2319     // by the destination where we're going to draw thing thing (ie this device). But we don't have
2320     // a color space, so we always decode in legacy mode for now.
2321     SkColorSpace* legacyColorSpace = nullptr;
2322     return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
2323                                          image->makeNonTextureImage(), legacyColorSpace);
2324 }
2325
2326 sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
2327     return nullptr;
2328 }
2329
2330 SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2331     // We always return a transient cache, so it is freed after each
2332     // filter traversal.
2333     return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2334 }