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 "SkCanvas.h"
15 #include "SkClipOpPriv.h"
16 #include "SkClusterator.h"
17 #include "SkColor.h"
18 #include "SkColorFilter.h"
19 #include "SkDraw.h"
20 #include "SkGlyphRun.h"
21 #include "SkImageFilterCache.h"
22 #include "SkJpegEncoder.h"
23 #include "SkMakeUnique.h"
24 #include "SkMaskFilterBase.h"
25 #include "SkPDFBitmap.h"
26 #include "SkPDFDocument.h"
27 #include "SkPDFDocumentPriv.h"
28 #include "SkPDFFont.h"
29 #include "SkPDFFormXObject.h"
30 #include "SkPDFGraphicState.h"
31 #include "SkPDFResourceDict.h"
32 #include "SkPDFShader.h"
33 #include "SkPDFTypes.h"
34 #include "SkPDFUtils.h"
35 #include "SkPath.h"
36 #include "SkPathEffect.h"
37 #include "SkPathOps.h"
38 #include "SkRRect.h"
39 #include "SkRasterClip.h"
40 #include "SkScopeExit.h"
41 #include "SkStrike.h"
42 #include "SkString.h"
43 #include "SkSurface.h"
44 #include "SkTemplates.h"
45 #include "SkTextBlob.h"
46 #include "SkTextFormatParams.h"
47 #include "SkTo.h"
48 #include "SkUTF.h"
49 #include "SkXfermodeInterpretation.h"
50 
51 #include <vector>
52 
53 #ifndef SK_PDF_MASK_QUALITY
54     // If MASK_QUALITY is in [0,100], will be used for JpegEncoder.
55     // Otherwise, just encode masks losslessly.
56     #define SK_PDF_MASK_QUALITY 50
57     // Since these masks are used for blurry shadows, we shouldn't need
58     // high quality.  Raise this value if your shadows have visible JPEG
59     // artifacts.
60     // If SkJpegEncoder::Encode fails, we will fall back to the lossless
61     // encoding.
62 #endif
63 
64 // Utility functions
65 
to_path(const SkRect & r)66 static SkPath to_path(const SkRect& r) {
67     SkPath p;
68     p.addRect(r);
69     return p;
70 }
71 
72 // This function destroys the mask and either frees or takes the pixels.
mask_to_greyscale_image(SkMask * mask)73 sk_sp<SkImage> mask_to_greyscale_image(SkMask* mask) {
74     sk_sp<SkImage> img;
75     SkPixmap pm(SkImageInfo::Make(mask->fBounds.width(), mask->fBounds.height(),
76                                   kGray_8_SkColorType, kOpaque_SkAlphaType),
77                 mask->fImage, mask->fRowBytes);
78     const int imgQuality = SK_PDF_MASK_QUALITY;
79     if (imgQuality <= 100 && imgQuality >= 0) {
80         SkDynamicMemoryWStream buffer;
81         SkJpegEncoder::Options jpegOptions;
82         jpegOptions.fQuality = imgQuality;
83         if (SkJpegEncoder::Encode(&buffer, pm, jpegOptions)) {
84             img = SkImage::MakeFromEncoded(buffer.detachAsData());
85             SkASSERT(img);
86             if (img) {
87                 SkMask::FreeImage(mask->fImage);
88             }
89         }
90     }
91     if (!img) {
92         img = SkImage::MakeFromRaster(pm, [](const void* p, void*) { SkMask::FreeImage((void*)p); },
93                                       nullptr);
94     }
95     *mask = SkMask();  // destructive;
96     return img;
97 }
98 
alpha_image_to_greyscale_image(const SkImage * mask)99 sk_sp<SkImage> alpha_image_to_greyscale_image(const SkImage* mask) {
100     int w = mask->width(), h = mask->height();
101     SkBitmap greyBitmap;
102     greyBitmap.allocPixels(SkImageInfo::Make(w, h, kGray_8_SkColorType, kOpaque_SkAlphaType));
103     if (!mask->readPixels(SkImageInfo::MakeA8(w, h),
104                           greyBitmap.getPixels(), greyBitmap.rowBytes(), 0, 0)) {
105         return nullptr;
106     }
107     return SkImage::MakeFromBitmap(greyBitmap);
108 }
109 
add_resource(SkTHashSet<SkPDFIndirectReference> & resources,SkPDFIndirectReference ref)110 static int add_resource(SkTHashSet<SkPDFIndirectReference>& resources, SkPDFIndirectReference ref) {
111     resources.add(ref);
112     return ref.fValue;
113 }
114 
draw_points(SkCanvas::PointMode mode,size_t count,const SkPoint * points,const SkPaint & paint,const SkIRect & bounds,const SkMatrix & ctm,SkBaseDevice * device)115 static void draw_points(SkCanvas::PointMode mode,
116                         size_t count,
117                         const SkPoint* points,
118                         const SkPaint& paint,
119                         const SkIRect& bounds,
120                         const SkMatrix& ctm,
121                         SkBaseDevice* device) {
122     SkRasterClip rc(bounds);
123     SkDraw draw;
124     draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
125     draw.fMatrix = &ctm;
126     draw.fRC = &rc;
127     draw.drawPoints(mode, count, points, paint, device);
128 }
129 
130 // If the paint will definitely draw opaquely, replace kSrc with
131 // kSrcOver.  http://crbug.com/473572
replace_srcmode_on_opaque_paint(SkPaint * paint)132 static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
133     if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
134         paint->setBlendMode(SkBlendMode::kSrcOver);
135     }
136 }
137 
138 // A shader's matrix is:  CTMM x LocalMatrix x WrappingLocalMatrix.  We want to
139 // switch to device space, where CTM = I, while keeping the original behavior.
140 //
141 //               I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
142 //                   LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
143 //  InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
144 //                                 NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
145 //
transform_shader(SkPaint * paint,const SkMatrix & ctm)146 static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
147     SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
148     SkMatrix lmInv;
149     if (lm.invert(&lmInv)) {
150         SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
151         paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
152     }
153 }
154 
emit_pdf_color(SkColor4f color,SkWStream * result)155 static void emit_pdf_color(SkColor4f color, SkWStream* result) {
156     SkASSERT(color.fA == 1);  // We handle alpha elsewhere.
157     SkPDFUtils::AppendColorComponentF(color.fR, result);
158     result->writeText(" ");
159     SkPDFUtils::AppendColorComponentF(color.fG, result);
160     result->writeText(" ");
161     SkPDFUtils::AppendColorComponentF(color.fB, result);
162     result->writeText(" ");
163 }
164 
165 // If the paint has a color filter, apply the color filter to the shader or the
166 // paint color.  Remove the color filter.
remove_color_filter(SkPaint * paint)167 void remove_color_filter(SkPaint* paint) {
168     if (SkColorFilter* cf = paint->getColorFilter()) {
169         if (SkShader* shader = paint->getShader()) {
170             paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
171         } else {
172             paint->setColor4f(cf->filterColor4f(paint->getColor4f(), nullptr), nullptr);
173         }
174         paint->setColorFilter(nullptr);
175     }
176 }
177 
GraphicStackState(SkDynamicMemoryWStream * s)178 SkPDFDevice::GraphicStackState::GraphicStackState(SkDynamicMemoryWStream* s) : fContentStream(s) {
179 }
180 
drainStack()181 void SkPDFDevice::GraphicStackState::drainStack() {
182     if (fContentStream) {
183         while (fStackDepth) {
184             this->pop();
185         }
186     }
187     SkASSERT(fStackDepth == 0);
188 }
189 
push()190 void SkPDFDevice::GraphicStackState::push() {
191     SkASSERT(fStackDepth < kMaxStackDepth);
192     fContentStream->writeText("q\n");
193     fStackDepth++;
194     fEntries[fStackDepth] = fEntries[fStackDepth - 1];
195 }
196 
pop()197 void SkPDFDevice::GraphicStackState::pop() {
198     SkASSERT(fStackDepth > 0);
199     fContentStream->writeText("Q\n");
200     fEntries[fStackDepth] = SkPDFDevice::GraphicStateEntry();
201     fStackDepth--;
202 }
203 
204 /* Calculate an inverted path's equivalent non-inverted path, given the
205  * canvas bounds.
206  * outPath may alias with invPath (since this is supported by PathOps).
207  */
calculate_inverse_path(const SkRect & bounds,const SkPath & invPath,SkPath * outPath)208 static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
209                                    SkPath* outPath) {
210     SkASSERT(invPath.isInverseFillType());
211     return Op(to_path(bounds), invPath, kIntersect_SkPathOp, outPath);
212 }
213 
rect_intersect(SkRect u,SkRect v)214 static SkRect rect_intersect(SkRect u, SkRect v) {
215     if (u.isEmpty() || v.isEmpty()) { return {0, 0, 0, 0}; }
216     return u.intersect(v) ? u : SkRect{0, 0, 0, 0};
217 }
218 
219 // Test to see if the clipstack is a simple rect, If so, we can avoid all PathOps code
220 // and speed thing up.
is_rect(const SkClipStack & clipStack,const SkRect & bounds,SkRect * dst)221 static bool is_rect(const SkClipStack& clipStack, const SkRect& bounds, SkRect* dst) {
222     SkRect currentClip = bounds;
223     SkClipStack::Iter iter(clipStack, SkClipStack::Iter::kBottom_IterStart);
224     while (const SkClipStack::Element* element = iter.next()) {
225         SkRect elementRect{0, 0, 0, 0};
226         switch (element->getDeviceSpaceType()) {
227             case SkClipStack::Element::DeviceSpaceType::kEmpty:
228                 break;
229             case SkClipStack::Element::DeviceSpaceType::kRect:
230                 elementRect = element->getDeviceSpaceRect();
231                 break;
232             default:
233                 return false;
234         }
235         switch (element->getOp()) {
236             case kReplace_SkClipOp:
237                 currentClip = rect_intersect(bounds, elementRect);
238                 break;
239             case SkClipOp::kIntersect:
240                 currentClip = rect_intersect(currentClip, elementRect);
241                 break;
242             default:
243                 return false;
244         }
245     }
246     *dst = currentClip;
247     return true;
248 }
249 
append_clip(const SkClipStack & clipStack,const SkIRect & bounds,SkWStream * wStream)250 static void append_clip(const SkClipStack& clipStack,
251                         const SkIRect& bounds,
252                         SkWStream* wStream) {
253     // The bounds are slightly outset to ensure this is correct in the
254     // face of floating-point accuracy and possible SkRegion bitmap
255     // approximations.
256     SkRect outsetBounds = SkRect::Make(bounds.makeOutset(1, 1));
257 
258     SkRect clipStackRect;
259     if (is_rect(clipStack, outsetBounds, &clipStackRect)) {
260         SkPDFUtils::AppendRectangle(clipStackRect, wStream);
261         wStream->writeText("W* n\n");
262         return;
263     }
264 
265     SkPath clipPath;
266     (void)clipStack.asPath(&clipPath);
267 
268     if (Op(clipPath, to_path(outsetBounds), kIntersect_SkPathOp, &clipPath)) {
269         SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, wStream);
270         SkPath::FillType clipFill = clipPath.getFillType();
271         NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
272         NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
273         if (clipFill == SkPath::kEvenOdd_FillType) {
274             wStream->writeText("W* n\n");
275         } else {
276             wStream->writeText("W n\n");
277         }
278     }
279     // If Op() fails (pathological case; e.g. input values are
280     // extremely large or NaN), emit no clip at all.
281 }
282 
283 // TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
284 // graphic state stack, and the fact that we can know all the clips used
285 // on the page to optimize this.
updateClip(const SkClipStack * clipStack,const SkIRect & bounds)286 void SkPDFDevice::GraphicStackState::updateClip(const SkClipStack* clipStack,
287                                                 const SkIRect& bounds) {
288     uint32_t clipStackGenID = clipStack ? clipStack->getTopmostGenID()
289                                         : SkClipStack::kWideOpenGenID;
290     if (clipStackGenID == currentEntry()->fClipStackGenID) {
291         return;
292     }
293 
294     while (fStackDepth > 0) {
295         this->pop();
296         if (clipStackGenID == currentEntry()->fClipStackGenID) {
297             return;
298         }
299     }
300     SkASSERT(currentEntry()->fClipStackGenID == SkClipStack::kWideOpenGenID);
301     if (clipStackGenID != SkClipStack::kWideOpenGenID) {
302         SkASSERT(clipStack);
303         this->push();
304 
305         currentEntry()->fClipStackGenID = clipStackGenID;
306         append_clip(*clipStack, bounds, fContentStream);
307     }
308 }
309 
append_transform(const SkMatrix & matrix,SkWStream * content)310 static void append_transform(const SkMatrix& matrix, SkWStream* content) {
311     SkScalar values[6];
312     if (!matrix.asAffine(values)) {
313         SkMatrix::SetAffineIdentity(values);
314     }
315     for (SkScalar v : values) {
316         SkPDFUtils::AppendScalar(v, content);
317         content->writeText(" ");
318     }
319     content->writeText("cm\n");
320 }
321 
updateMatrix(const SkMatrix & matrix)322 void SkPDFDevice::GraphicStackState::updateMatrix(const SkMatrix& matrix) {
323     if (matrix == currentEntry()->fMatrix) {
324         return;
325     }
326 
327     if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
328         SkASSERT(fStackDepth > 0);
329         SkASSERT(fEntries[fStackDepth].fClipStackGenID ==
330                  fEntries[fStackDepth -1].fClipStackGenID);
331         this->pop();
332 
333         SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
334     }
335     if (matrix.getType() == SkMatrix::kIdentity_Mask) {
336         return;
337     }
338 
339     this->push();
340     append_transform(matrix, fContentStream);
341     currentEntry()->fMatrix = matrix;
342 }
343 
updateDrawingState(const SkPDFDevice::GraphicStateEntry & state)344 void SkPDFDevice::GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
345     // PDF treats a shader as a color, so we only set one or the other.
346     if (state.fShaderIndex >= 0) {
347         if (state.fShaderIndex != currentEntry()->fShaderIndex) {
348             SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
349             currentEntry()->fShaderIndex = state.fShaderIndex;
350         }
351     } else {
352         if (state.fColor != currentEntry()->fColor ||
353                 currentEntry()->fShaderIndex >= 0) {
354             emit_pdf_color(state.fColor, fContentStream);
355             fContentStream->writeText("RG ");
356             emit_pdf_color(state.fColor, fContentStream);
357             fContentStream->writeText("rg\n");
358             currentEntry()->fColor = state.fColor;
359             currentEntry()->fShaderIndex = -1;
360         }
361     }
362 
363     if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
364         SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
365         currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
366     }
367 
368     if (state.fTextScaleX) {
369         if (state.fTextScaleX != currentEntry()->fTextScaleX) {
370             SkScalar pdfScale = state.fTextScaleX * 100;
371             SkPDFUtils::AppendScalar(pdfScale, fContentStream);
372             fContentStream->writeText(" Tz\n");
373             currentEntry()->fTextScaleX = state.fTextScaleX;
374         }
375     }
376 }
377 
onCreateDevice(const CreateInfo & cinfo,const SkPaint * layerPaint)378 SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
379     // PDF does not support image filters, so render them on CPU.
380     // Note that this rendering is done at "screen" resolution (100dpi), not
381     // printer resolution.
382 
383     // TODO: It may be possible to express some filters natively using PDF
384     // to improve quality and file size (https://bug.skia.org/3043)
385     if (layerPaint && (layerPaint->getImageFilter() || layerPaint->getColorFilter())) {
386         // need to return a raster device, which we will detect in drawDevice()
387         return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
388     }
389     return new SkPDFDevice(cinfo.fInfo.dimensions(), fDocument);
390 }
391 
392 // A helper class to automatically finish a ContentEntry at the end of a
393 // drawing method and maintain the state needed between set up and finish.
394 class ScopedContentEntry {
395 public:
ScopedContentEntry(SkPDFDevice * device,const SkClipStack * clipStack,const SkMatrix & matrix,const SkPaint & paint,SkScalar textScale=0)396     ScopedContentEntry(SkPDFDevice* device,
397                        const SkClipStack* clipStack,
398                        const SkMatrix& matrix,
399                        const SkPaint& paint,
400                        SkScalar textScale = 0)
401         : fDevice(device)
402         , fBlendMode(SkBlendMode::kSrcOver)
403         , fClipStack(clipStack)
404     {
405         if (matrix.hasPerspective()) {
406             NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
407             return;
408         }
409         fBlendMode = paint.getBlendMode();
410         fContentStream =
411             fDevice->setUpContentEntry(clipStack, matrix, paint, textScale, &fDstFormXObject);
412     }
ScopedContentEntry(SkPDFDevice * dev,const SkPaint & paint,SkScalar textScale=0)413     ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, SkScalar textScale = 0)
414         : ScopedContentEntry(dev, &dev->cs(), dev->ctm(), paint, textScale) {}
415 
~ScopedContentEntry()416     ~ScopedContentEntry() {
417         if (fContentStream) {
418             SkPath* shape = &fShape;
419             if (shape->isEmpty()) {
420                 shape = nullptr;
421             }
422             fDevice->finishContentEntry(fClipStack, fBlendMode, fDstFormXObject, shape);
423         }
424     }
425 
operator bool() const426     explicit operator bool() const { return fContentStream != nullptr; }
stream()427     SkDynamicMemoryWStream* stream() { return fContentStream; }
428 
429     /* Returns true when we explicitly need the shape of the drawing. */
needShape()430     bool needShape() {
431         switch (fBlendMode) {
432             case SkBlendMode::kClear:
433             case SkBlendMode::kSrc:
434             case SkBlendMode::kSrcIn:
435             case SkBlendMode::kSrcOut:
436             case SkBlendMode::kDstIn:
437             case SkBlendMode::kDstOut:
438             case SkBlendMode::kSrcATop:
439             case SkBlendMode::kDstATop:
440             case SkBlendMode::kModulate:
441                 return true;
442             default:
443                 return false;
444         }
445     }
446 
447     /* Returns true unless we only need the shape of the drawing. */
needSource()448     bool needSource() {
449         if (fBlendMode == SkBlendMode::kClear) {
450             return false;
451         }
452         return true;
453     }
454 
455     /* If the shape is different than the alpha component of the content, then
456      * setShape should be called with the shape.  In particular, images and
457      * devices have rectangular shape.
458      */
setShape(const SkPath & shape)459     void setShape(const SkPath& shape) {
460         fShape = shape;
461     }
462 
463 private:
464     SkPDFDevice* fDevice = nullptr;
465     SkDynamicMemoryWStream* fContentStream = nullptr;
466     SkBlendMode fBlendMode;
467     SkPDFIndirectReference fDstFormXObject;
468     SkPath fShape;
469     const SkClipStack* fClipStack;
470 };
471 
472 ////////////////////////////////////////////////////////////////////////////////
473 
SkPDFDevice(SkISize pageSize,SkPDFDocument * doc,const SkMatrix & transform)474 SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc, const SkMatrix& transform)
475     : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
476                 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
477     , fInitialTransform(transform)
478     , fNodeId(0)
479     , fDocument(doc)
480 {
481     SkASSERT(!pageSize.isEmpty());
482 }
483 
484 SkPDFDevice::~SkPDFDevice() = default;
485 
reset()486 void SkPDFDevice::reset() {
487     fLinkToURLs = std::vector<RectWithData>();
488     fLinkToDestinations = std::vector<RectWithData>();
489     fNamedDestinations = std::vector<NamedDestination>();
490     fGraphicStateResources.reset();
491     fXObjectResources.reset();
492     fShaderResources.reset();
493     fFontResources.reset();
494     fContent.reset();
495     fActiveStackState = GraphicStackState();
496 }
497 
drawAnnotation(const SkRect & rect,const char key[],SkData * value)498 void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
499     if (!value) {
500         return;
501     }
502     if (rect.isEmpty()) {
503         if (!strcmp(key, SkPDFGetNodeIdKey())) {
504             int nodeID;
505             if (value->size() != sizeof(nodeID)) { return; }
506             memcpy(&nodeID, value->data(), sizeof(nodeID));
507             fNodeId = nodeID;
508             return;
509         }
510         if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
511             SkPoint transformedPoint;
512             this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
513             fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
514         }
515         return;
516     }
517     // Convert to path to handle non-90-degree rotations.
518     SkPath path = to_path(rect);
519     path.transform(this->ctm(), &path);
520     SkPath clip;
521     (void)this->cs().asPath(&clip);
522     Op(clip, path, kIntersect_SkPathOp, &path);
523     // PDF wants a rectangle only.
524     SkRect transformedRect = path.getBounds();
525     if (transformedRect.isEmpty()) {
526         return;
527     }
528     if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
529         fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
530     } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
531         fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
532     }
533 }
534 
drawPaint(const SkPaint & srcPaint)535 void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
536     SkMatrix inverse;
537     if (!this->ctm().invert(&inverse)) {
538         return;
539     }
540     SkRect bbox = this->cs().bounds(this->bounds());
541     inverse.mapRect(&bbox);
542     bbox.roundOut(&bbox);
543     if (this->hasEmptyClip()) {
544         return;
545     }
546     SkPaint newPaint = srcPaint;
547     newPaint.setStyle(SkPaint::kFill_Style);
548     this->drawRect(bbox, newPaint);
549 }
550 
drawPoints(SkCanvas::PointMode mode,size_t count,const SkPoint * points,const SkPaint & srcPaint)551 void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
552                              size_t count,
553                              const SkPoint* points,
554                              const SkPaint& srcPaint) {
555     if (this->hasEmptyClip()) {
556         return;
557     }
558     SkPaint passedPaint = srcPaint;
559     remove_color_filter(&passedPaint);
560     replace_srcmode_on_opaque_paint(&passedPaint);
561     if (SkCanvas::kPoints_PointMode != mode) {
562         passedPaint.setStyle(SkPaint::kStroke_Style);
563     }
564     if (count == 0) {
565         return;
566     }
567 
568     // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
569     // We only use this when there's a path effect because of the overhead
570     // of multiple calls to setUpContentEntry it causes.
571     if (passedPaint.getPathEffect()) {
572         draw_points(mode, count, points, passedPaint,
573                     this->devClipBounds(), this->ctm(), this);
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                 this->drawRect(r, modifiedPaint);
594             }
595             return;
596         } else {
597             modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
598         }
599     }
600 
601     ScopedContentEntry content(this, *paint);
602     if (!content) {
603         return;
604     }
605     SkDynamicMemoryWStream* contentStream = content.stream();
606     switch (mode) {
607         case SkCanvas::kPolygon_PointMode:
608             SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
609             for (size_t i = 1; i < count; i++) {
610                 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
611             }
612             SkPDFUtils::StrokePath(contentStream);
613             break;
614         case SkCanvas::kLines_PointMode:
615             for (size_t i = 0; i < count/2; i++) {
616                 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
617                 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
618                 SkPDFUtils::StrokePath(contentStream);
619             }
620             break;
621         case SkCanvas::kPoints_PointMode:
622             SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
623             for (size_t i = 0; i < count; i++) {
624                 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
625                 SkPDFUtils::ClosePath(contentStream);
626                 SkPDFUtils::StrokePath(contentStream);
627             }
628             break;
629         default:
630             SkASSERT(false);
631     }
632 }
633 
create_link_annotation(const SkRect & translatedRect)634 static std::unique_ptr<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
635     auto annotation = SkPDFMakeDict("Annot");
636     annotation->insertName("Subtype", "Link");
637     annotation->insertInt("F", 4);  // required by ISO 19005
638     // Border: 0 = Horizontal corner radius.
639     //         0 = Vertical corner radius.
640     //         0 = Width, 0 = no border.
641     annotation->insertObject("Border", SkPDFMakeArray(0, 0, 0));
642 
643     annotation->insertObject("Rect", SkPDFMakeArray(translatedRect.fLeft,
644                                                     translatedRect.fTop,
645                                                     translatedRect.fRight,
646                                                     translatedRect.fBottom));
647     return annotation;
648 }
649 
create_link_to_url(const SkData * urlData,const SkRect & r)650 static std::unique_ptr<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
651     std::unique_ptr<SkPDFDict> annotation = create_link_annotation(r);
652     SkString url(static_cast<const char *>(urlData->data()),
653                  urlData->size() - 1);
654     auto action = SkPDFMakeDict("Action");
655     action->insertName("S", "URI");
656     action->insertString("URI", url);
657     annotation->insertObject("A", std::move(action));
658     return annotation;
659 }
660 
create_link_named_dest(const SkData * nameData,const SkRect & r)661 static std::unique_ptr<SkPDFDict> create_link_named_dest(const SkData* nameData,
662                                                          const SkRect& r) {
663     std::unique_ptr<SkPDFDict> annotation = create_link_annotation(r);
664     SkString name(static_cast<const char *>(nameData->data()),
665                   nameData->size() - 1);
666     annotation->insertName("Dest", name);
667     return annotation;
668 }
669 
drawRect(const SkRect & rect,const SkPaint & srcPaint)670 void SkPDFDevice::drawRect(const SkRect& rect,
671                            const SkPaint& srcPaint) {
672     if (this->hasEmptyClip()) {
673         return;
674     }
675     SkPaint paint = srcPaint;
676     remove_color_filter(&paint);
677     replace_srcmode_on_opaque_paint(&paint);
678     SkRect r = rect;
679     r.sort();
680 
681     if (paint.getPathEffect() || paint.getMaskFilter() || this->ctm().hasPerspective()) {
682         this->drawPath(to_path(r), paint, true);
683         return;
684     }
685 
686     ScopedContentEntry content(this, paint);
687     if (!content) {
688         return;
689     }
690     SkPDFUtils::AppendRectangle(r, content.stream());
691     SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
692 }
693 
drawRRect(const SkRRect & rrect,const SkPaint & srcPaint)694 void SkPDFDevice::drawRRect(const SkRRect& rrect,
695                             const SkPaint& srcPaint) {
696     if (this->hasEmptyClip()) {
697         return;
698     }
699     SkPaint paint = srcPaint;
700     remove_color_filter(&paint);
701     replace_srcmode_on_opaque_paint(&paint);
702     SkPath  path;
703     path.addRRect(rrect);
704     this->drawPath(path, paint, true);
705 }
706 
drawOval(const SkRect & oval,const SkPaint & srcPaint)707 void SkPDFDevice::drawOval(const SkRect& oval,
708                            const SkPaint& srcPaint) {
709     if (this->hasEmptyClip()) {
710         return;
711     }
712     SkPaint paint = srcPaint;
713     remove_color_filter(&paint);
714     replace_srcmode_on_opaque_paint(&paint);
715     SkPath  path;
716     path.addOval(oval);
717     this->drawPath(path, paint, true);
718 }
719 
drawPath(const SkPath & origPath,const SkPaint & srcPaint,bool pathIsMutable)720 void SkPDFDevice::drawPath(const SkPath& origPath,
721                            const SkPaint& srcPaint,
722                            bool pathIsMutable) {
723     this->internalDrawPath(this->cs(), this->ctm(), origPath, srcPaint, pathIsMutable);
724 }
725 
internalDrawPathWithFilter(const SkClipStack & clipStack,const SkMatrix & ctm,const SkPath & origPath,const SkPaint & origPaint)726 void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
727                                              const SkMatrix& ctm,
728                                              const SkPath& origPath,
729                                              const SkPaint& origPaint) {
730     SkASSERT(origPaint.getMaskFilter());
731     SkPath path(origPath);
732     SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
733 
734     SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
735                                      ? SkStrokeRec::kFill_InitStyle
736                                      : SkStrokeRec::kHairline_InitStyle;
737     path.transform(ctm, &path);
738 
739     SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
740     SkMask sourceMask;
741     if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
742                             &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
743                             initStyle)) {
744         return;
745     }
746     SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
747     SkMask dstMask;
748     SkIPoint margin;
749     if (!as_MFB(paint->getMaskFilter())->filterMask(&dstMask, sourceMask, ctm, &margin)) {
750         return;
751     }
752     SkIRect dstMaskBounds = dstMask.fBounds;
753     sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
754     // PDF doesn't seem to allow masking vector graphics with an Image XObject.
755     // Must mask with a Form XObject.
756     sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
757     {
758         SkCanvas canvas(maskDevice);
759         canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
760     }
761     if (!ctm.isIdentity() && paint->getShader()) {
762         transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
763     }
764     ScopedContentEntry content(this, &clipStack, SkMatrix::I(), *paint);
765     if (!content) {
766         return;
767     }
768     this->addSMaskGraphicState(std::move(maskDevice), content.stream());
769     SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
770     SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
771     this->clearMaskOnGraphicState(content.stream());
772 }
773 
setGraphicState(SkPDFIndirectReference gs,SkDynamicMemoryWStream * content)774 void SkPDFDevice::setGraphicState(SkPDFIndirectReference gs, SkDynamicMemoryWStream* content) {
775     SkPDFUtils::ApplyGraphicState(add_resource(fGraphicStateResources, gs), content);
776 }
777 
addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,SkDynamicMemoryWStream * contentStream)778 void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
779                                        SkDynamicMemoryWStream* contentStream) {
780     this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
781             maskDevice->makeFormXObjectFromDevice(true), false,
782             SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), contentStream);
783 }
784 
clearMaskOnGraphicState(SkDynamicMemoryWStream * contentStream)785 void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
786     // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
787     SkPDFIndirectReference& noSMaskGS = fDocument->fNoSmaskGraphicState;
788     if (!noSMaskGS) {
789         SkPDFDict tmp("ExtGState");
790         tmp.insertName("SMask", "None");
791         noSMaskGS = fDocument->emit(tmp);
792     }
793     this->setGraphicState(noSMaskGS, contentStream);
794 }
795 
internalDrawPath(const SkClipStack & clipStack,const SkMatrix & ctm,const SkPath & origPath,const SkPaint & srcPaint,bool pathIsMutable)796 void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
797                                    const SkMatrix& ctm,
798                                    const SkPath& origPath,
799                                    const SkPaint& srcPaint,
800                                    bool pathIsMutable) {
801     if (clipStack.isEmpty(this->bounds())) {
802         return;
803     }
804     SkPaint paint = srcPaint;
805     remove_color_filter(&paint);
806     replace_srcmode_on_opaque_paint(&paint);
807     SkPath modifiedPath;
808     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
809 
810     if (paint.getMaskFilter()) {
811         this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint);
812         return;
813     }
814 
815     SkMatrix matrix = ctm;
816 
817     if (paint.getPathEffect()) {
818         if (clipStack.isEmpty(this->bounds())) {
819             return;
820         }
821         if (!pathIsMutable) {
822             modifiedPath = origPath;
823             pathPtr = &modifiedPath;
824             pathIsMutable = true;
825         }
826         if (paint.getFillPath(*pathPtr, pathPtr)) {
827             paint.setStyle(SkPaint::kFill_Style);
828         } else {
829             paint.setStyle(SkPaint::kStroke_Style);
830             paint.setStrokeWidth(0);
831         }
832         paint.setPathEffect(nullptr);
833     }
834 
835     if (this->handleInversePath(*pathPtr, paint, pathIsMutable)) {
836         return;
837     }
838     if (matrix.getType() & SkMatrix::kPerspective_Mask) {
839         if (!pathIsMutable) {
840             modifiedPath = origPath;
841             pathPtr = &modifiedPath;
842             pathIsMutable = true;
843         }
844         pathPtr->transform(matrix);
845         if (paint.getShader()) {
846             transform_shader(&paint, matrix);
847         }
848         matrix = SkMatrix::I();
849     }
850 
851     ScopedContentEntry content(this, &clipStack, matrix, paint);
852     if (!content) {
853         return;
854     }
855     constexpr SkScalar kToleranceScale = 0.0625f;  // smaller = better conics (circles).
856     SkScalar matrixScale = matrix.mapRadius(1.0f);
857     SkScalar tolerance = matrixScale > 0.0f ? kToleranceScale / matrixScale : kToleranceScale;
858     bool consumeDegeratePathSegments =
859            paint.getStyle() == SkPaint::kFill_Style ||
860            (paint.getStrokeCap() != SkPaint::kRound_Cap &&
861             paint.getStrokeCap() != SkPaint::kSquare_Cap);
862     SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
863                          tolerance);
864     SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
865 }
866 
867 ////////////////////////////////////////////////////////////////////////////////
868 
drawImageRect(const SkImage * image,const SkRect * src,const SkRect & dst,const SkPaint & paint,SkCanvas::SrcRectConstraint)869 void SkPDFDevice::drawImageRect(const SkImage* image,
870                                 const SkRect* src,
871                                 const SkRect& dst,
872                                 const SkPaint& paint,
873                                 SkCanvas::SrcRectConstraint) {
874     SkASSERT(image);
875     this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
876                                 src, dst, paint, this->ctm());
877 }
878 
drawBitmapRect(const SkBitmap & bm,const SkRect * src,const SkRect & dst,const SkPaint & paint,SkCanvas::SrcRectConstraint)879 void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
880                                  const SkRect* src,
881                                  const SkRect& dst,
882                                  const SkPaint& paint,
883                                  SkCanvas::SrcRectConstraint) {
884     SkASSERT(!bm.drawsNothing());
885     this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
886 }
887 
drawBitmap(const SkBitmap & bm,SkScalar x,SkScalar y,const SkPaint & paint)888 void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
889     SkASSERT(!bm.drawsNothing());
890     auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
891     this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
892 }
893 
drawSprite(const SkBitmap & bm,int x,int y,const SkPaint & paint)894 void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
895     SkASSERT(!bm.drawsNothing());
896     auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
897     this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
898 }
899 
drawImage(const SkImage * image,SkScalar x,SkScalar y,const SkPaint & paint)900 void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
901     SkASSERT(image);
902     auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
903     this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
904                                 nullptr, r, paint, this->ctm());
905 }
906 
907 ////////////////////////////////////////////////////////////////////////////////
908 
909 namespace {
910 class GlyphPositioner {
911 public:
GlyphPositioner(SkDynamicMemoryWStream * content,SkScalar textSkewX,SkPoint origin)912     GlyphPositioner(SkDynamicMemoryWStream* content,
913                     SkScalar textSkewX,
914                     SkPoint origin)
915         : fContent(content)
916         , fCurrentMatrixOrigin(origin)
917         , fTextSkewX(textSkewX) {
918     }
~GlyphPositioner()919     ~GlyphPositioner() { this->flush(); }
flush()920     void flush() {
921         if (fInText) {
922             fContent->writeText("> Tj\n");
923             fInText = false;
924         }
925     }
setWideChars(bool wide)926     void setWideChars(bool wide) {
927         this->flush();
928         fWideChars = wide;
929     }
writeGlyph(SkPoint xy,SkScalar advanceWidth,uint16_t glyph)930     void writeGlyph(SkPoint xy,
931                     SkScalar advanceWidth,
932                     uint16_t glyph) {
933         if (!fInitialized) {
934             // Flip the text about the x-axis to account for origin swap and include
935             // the passed parameters.
936             fContent->writeText("1 0 ");
937             SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
938             fContent->writeText(" -1 ");
939             SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
940             fContent->writeText(" ");
941             SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
942             fContent->writeText(" Tm\n");
943             fCurrentMatrixOrigin.set(0.0f, 0.0f);
944             fInitialized = true;
945         }
946         SkPoint position = xy - fCurrentMatrixOrigin;
947         if (position != SkPoint{fXAdvance, 0}) {
948             this->flush();
949             SkPDFUtils::AppendScalar(position.x() - position.y() * fTextSkewX, fContent);
950             fContent->writeText(" ");
951             SkPDFUtils::AppendScalar(-position.y(), fContent);
952             fContent->writeText(" Td ");
953             fCurrentMatrixOrigin = xy;
954             fXAdvance = 0;
955         }
956         fXAdvance += advanceWidth;
957         if (!fInText) {
958             fContent->writeText("<");
959             fInText = true;
960         }
961         if (fWideChars) {
962             SkPDFUtils::WriteUInt16BE(fContent, glyph);
963         } else {
964             SkASSERT(0 == glyph >> 8);
965             SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
966         }
967     }
968 
969 private:
970     SkDynamicMemoryWStream* fContent;
971     SkPoint fCurrentMatrixOrigin;
972     SkScalar fXAdvance = 0.0f;
973     SkScalar fTextSkewX;
974     bool fWideChars = true;
975     bool fInText = false;
976     bool fInitialized = false;
977 };
978 }  // namespace
979 
map_glyph(const std::vector<SkUnichar> & glyphToUnicode,SkGlyphID glyph)980 static SkUnichar map_glyph(const std::vector<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
981     return glyph < glyphToUnicode.size() ? glyphToUnicode[SkToInt(glyph)] : -1;
982 }
983 
984 namespace {
985 struct PositionedGlyph {
986     SkPoint fPos;
987     SkGlyphID fGlyph;
988 };
989 }
990 
get_glyph_bounds_device_space(SkGlyphID gid,SkStrike * cache,SkScalar xScale,SkScalar yScale,SkPoint xy,const SkMatrix & ctm)991 static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkStrike* cache,
992                                             SkScalar xScale, SkScalar yScale,
993                                             SkPoint xy, const SkMatrix& ctm) {
994     const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
995     SkRect glyphBounds = {glyph.fLeft * xScale,
996                           glyph.fTop * yScale,
997                           (glyph.fLeft + glyph.fWidth) * xScale,
998                           (glyph.fTop + glyph.fHeight) * yScale};
999     glyphBounds.offset(xy);
1000     ctm.mapRect(&glyphBounds); // now in dev space.
1001     return glyphBounds;
1002 }
1003 
contains(const SkRect & r,SkPoint p)1004 static bool contains(const SkRect& r, SkPoint p) {
1005    return r.left() <= p.x() && p.x() <= r.right() &&
1006           r.top()  <= p.y() && p.y() <= r.bottom();
1007 }
1008 
drawGlyphRunAsPath(const SkGlyphRun & glyphRun,SkPoint offset,const SkPaint & runPaint)1009 void SkPDFDevice::drawGlyphRunAsPath(
1010         const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
1011     const SkFont& font = glyphRun.font();
1012     SkPath path;
1013 
1014     struct Rec {
1015         SkPath* fPath;
1016         SkPoint fOffset;
1017         const SkPoint* fPos;
1018     } rec = {&path, offset, glyphRun.positions().data()};
1019 
1020     font.getPaths(glyphRun.glyphsIDs().data(), glyphRun.glyphsIDs().size(),
1021                   [](const SkPath* path, const SkMatrix& mx, void* ctx) {
1022                       Rec* rec = reinterpret_cast<Rec*>(ctx);
1023                       if (path) {
1024                           SkMatrix total = mx;
1025                           total.postTranslate(rec->fPos->fX + rec->fOffset.fX,
1026                                               rec->fPos->fY + rec->fOffset.fY);
1027                           rec->fPath->addPath(*path, total);
1028                       }
1029                       rec->fPos += 1; // move to the next glyph's position
1030                   }, &rec);
1031     this->drawPath(path, runPaint, true);
1032 
1033     SkFont transparentFont = glyphRun.font();
1034     transparentFont.setEmbolden(false); // Stop Recursion
1035     SkGlyphRun tmpGlyphRun(glyphRun, transparentFont);
1036 
1037     SkPaint transparent;
1038     transparent.setColor(SK_ColorTRANSPARENT);
1039 
1040     if (this->ctm().hasPerspective()) {
1041         SkMatrix prevCTM = this->ctm();
1042         this->setCTM(SkMatrix::I());
1043         this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
1044         this->setCTM(prevCTM);
1045     } else {
1046         this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
1047     }
1048 }
1049 
needs_new_font(SkPDFFont * font,SkGlyphID gid,SkStrike * cache,SkAdvancedTypefaceMetrics::FontType fontType)1050 static bool needs_new_font(SkPDFFont* font, SkGlyphID gid, SkStrike* cache,
1051                            SkAdvancedTypefaceMetrics::FontType fontType) {
1052     if (!font || !font->hasGlyph(gid)) {
1053         return true;
1054     }
1055     if (fontType == SkAdvancedTypefaceMetrics::kOther_Font) {
1056         return false;
1057     }
1058     const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1059     if (glyph.isEmpty()) {
1060         return false;
1061     }
1062 
1063     bool bitmapOnly = nullptr == cache->findPath(glyph);
1064     bool convertedToType3 = (font->getType() == SkAdvancedTypefaceMetrics::kOther_Font);
1065     return convertedToType3 != bitmapOnly;
1066 }
1067 
internalDrawGlyphRun(const SkGlyphRun & glyphRun,SkPoint offset,const SkPaint & runPaint)1068 void SkPDFDevice::internalDrawGlyphRun(
1069         const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
1070 
1071     const SkGlyphID* glyphs = glyphRun.glyphsIDs().data();
1072     uint32_t glyphCount = SkToU32(glyphRun.glyphsIDs().size());
1073     const SkFont& glyphRunFont = glyphRun.font();
1074 
1075     if (!glyphCount || !glyphs || glyphRunFont.getSize() <= 0 || this->hasEmptyClip()) {
1076         return;
1077     }
1078     if (runPaint.getPathEffect()
1079         || runPaint.getMaskFilter()
1080         || glyphRunFont.isEmbolden()
1081         || this->ctm().hasPerspective()
1082         || SkPaint::kFill_Style != runPaint.getStyle()) {
1083         // Stroked Text doesn't work well with Type3 fonts.
1084         this->drawGlyphRunAsPath(glyphRun, offset, runPaint);
1085         return;
1086     }
1087     SkTypeface* typeface = glyphRunFont.getTypefaceOrDefault();
1088     if (!typeface) {
1089         SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1090         return;
1091     }
1092 
1093     const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, fDocument);
1094     if (!metrics) {
1095         return;
1096     }
1097     SkAdvancedTypefaceMetrics::FontType fontType = SkPDFFont::FontType(*metrics);
1098 
1099     const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(typeface, fDocument);
1100 
1101     SkClusterator clusterator(glyphRun);
1102 
1103     int emSize;
1104     auto glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
1105 
1106     SkScalar textSize = glyphRunFont.getSize();
1107     SkScalar advanceScale = textSize * glyphRunFont.getScaleX() / emSize;
1108 
1109     // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1110     SkScalar textScaleY = textSize / emSize;
1111     SkScalar textScaleX = advanceScale + glyphRunFont.getSkewX() * textScaleY;
1112 
1113     SkRect clipStackBounds = this->cs().bounds(this->bounds());
1114 
1115     SkPaint paint(runPaint);
1116     remove_color_filter(&paint);
1117     replace_srcmode_on_opaque_paint(&paint);
1118     ScopedContentEntry content(this, paint, glyphRunFont.getScaleX());
1119     if (!content) {
1120         return;
1121     }
1122     SkDynamicMemoryWStream* out = content.stream();
1123 
1124     out->writeText("BT\n");
1125 
1126     int markId = -1;
1127     if (fNodeId) {
1128         markId = fDocument->getMarkIdForNodeId(fNodeId);
1129     }
1130 
1131     if (markId != -1) {
1132         out->writeText("/P <</MCID ");
1133         out->writeDecAsText(markId);
1134         out->writeText(" >>BDC\n");
1135     }
1136     SK_AT_SCOPE_EXIT(if (markId != -1) out->writeText("EMC\n"));
1137 
1138     SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1139 
1140     const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1141 
1142     if (clusterator.reversedChars()) {
1143         out->writeText("/ReversedChars BMC\n");
1144     }
1145     SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1146     GlyphPositioner glyphPositioner(out, glyphRunFont.getSkewX(), offset);
1147     SkPDFFont* font = nullptr;
1148 
1149     while (SkClusterator::Cluster c = clusterator.next()) {
1150         int index = c.fGlyphIndex;
1151         int glyphLimit = index + c.fGlyphCount;
1152 
1153         bool actualText = false;
1154         SK_AT_SCOPE_EXIT(if (actualText) {
1155                              glyphPositioner.flush();
1156                              out->writeText("EMC\n");
1157                          });
1158         if (c.fUtf8Text) {  // real cluster
1159             // Check if `/ActualText` needed.
1160             const char* textPtr = c.fUtf8Text;
1161             const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1162             SkUnichar unichar = SkUTF::NextUTF8(&textPtr, textEnd);
1163             if (unichar < 0) {
1164                 return;
1165             }
1166             if (textPtr < textEnd ||                                  // more characters left
1167                 glyphLimit > index + 1 ||                             // toUnicode wouldn't work
1168                 unichar != map_glyph(glyphToUnicode, glyphs[index]))  // test single Unichar map
1169             {
1170                 glyphPositioner.flush();
1171                 out->writeText("/Span<</ActualText <");
1172                 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF);  // U+FEFF = BYTE ORDER MARK
1173                 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1174                 SkPDFUtils::WriteUTF16beHex(out, unichar);  // first char
1175                 while (textPtr < textEnd) {
1176                     unichar = SkUTF::NextUTF8(&textPtr, textEnd);
1177                     if (unichar < 0) {
1178                         break;
1179                     }
1180                     SkPDFUtils::WriteUTF16beHex(out, unichar);
1181                 }
1182                 out->writeText("> >> BDC\n");  // begin marked-content sequence
1183                                                // with an associated property list.
1184                 actualText = true;
1185             }
1186         }
1187         for (; index < glyphLimit; ++index) {
1188             SkGlyphID gid = glyphs[index];
1189             if (gid > maxGlyphID) {
1190                 continue;
1191             }
1192             SkPoint xy = glyphRun.positions()[index];
1193             // Do a glyph-by-glyph bounds-reject if positions are absolute.
1194             SkRect glyphBounds = get_glyph_bounds_device_space(
1195                     gid, glyphCache.get(), textScaleX, textScaleY,
1196                     xy + offset, this->ctm());
1197             if (glyphBounds.isEmpty()) {
1198                 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1199                     continue;
1200                 }
1201             } else {
1202                 if (!clipStackBounds.intersects(glyphBounds)) {
1203                     continue;  // reject glyphs as out of bounds
1204                 }
1205             }
1206             if (needs_new_font(font, gid, glyphCache.get(), fontType)) {
1207                 // Not yet specified font or need to switch font.
1208                 font = SkPDFFont::GetFontResource(fDocument, glyphCache.get(), typeface, gid);
1209                 SkASSERT(font);  // All preconditions for SkPDFFont::GetFontResource are met.
1210                 glyphPositioner.flush();
1211                 glyphPositioner.setWideChars(font->multiByteGlyphs());
1212                 SkPDFWriteResourceName(out, SkPDFResourceType::kFont,
1213                                        add_resource(fFontResources, font->indirectReference()));
1214                 out->writeText(" ");
1215                 SkPDFUtils::AppendScalar(textSize, out);
1216                 out->writeText(" Tf\n");
1217 
1218             }
1219             font->noteGlyphUsage(gid);
1220             SkGlyphID encodedGlyph = font->multiByteGlyphs()
1221                                    ? gid : font->glyphToPDFFontEncoding(gid);
1222             SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1223             glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1224         }
1225     }
1226 }
1227 
drawGlyphRunList(const SkGlyphRunList & glyphRunList)1228 void SkPDFDevice::drawGlyphRunList(const SkGlyphRunList& glyphRunList) {
1229     for (const SkGlyphRun& glyphRun : glyphRunList) {
1230         this->internalDrawGlyphRun(glyphRun, glyphRunList.origin(), glyphRunList.paint());
1231     }
1232 }
1233 
drawVertices(const SkVertices *,const SkVertices::Bone[],int,SkBlendMode,const SkPaint &)1234 void SkPDFDevice::drawVertices(const SkVertices*, const SkVertices::Bone[], int, SkBlendMode,
1235                                const SkPaint&) {
1236     if (this->hasEmptyClip()) {
1237         return;
1238     }
1239     // TODO: implement drawVertices
1240 }
1241 
drawFormXObject(SkPDFIndirectReference xObject,SkDynamicMemoryWStream * content)1242 void SkPDFDevice::drawFormXObject(SkPDFIndirectReference xObject, SkDynamicMemoryWStream* content) {
1243     SkASSERT(xObject);
1244     SkPDFWriteResourceName(content, SkPDFResourceType::kXObject,
1245                            add_resource(fXObjectResources, xObject));
1246     content->writeText(" Do\n");
1247 }
1248 
drawDevice(SkBaseDevice * device,int x,int y,const SkPaint & paint)1249 void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
1250     SkASSERT(!paint.getImageFilter());
1251 
1252     // Check if the source device is really a bitmapdevice (because that's what we returned
1253     // from createDevice (likely due to an imagefilter)
1254     SkPixmap pmap;
1255     if (device->peekPixels(&pmap)) {
1256         SkBitmap bitmap;
1257         bitmap.installPixels(pmap);
1258         this->drawSprite(bitmap, x, y, paint);
1259         return;
1260     }
1261 
1262     // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
1263     SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
1264 
1265     SkScalar scalarX = SkIntToScalar(x);
1266     SkScalar scalarY = SkIntToScalar(y);
1267     for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1268         SkRect r = l.rect.makeOffset(scalarX, scalarY);
1269         fLinkToURLs.emplace_back(RectWithData{r, l.data});
1270     }
1271     for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1272         SkRect r = l.rect.makeOffset(scalarX, scalarY);
1273         fLinkToDestinations.emplace_back(RectWithData{r, l.data});
1274     }
1275     for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1276         SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
1277         fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
1278     }
1279 
1280     if (pdfDevice->isContentEmpty()) {
1281         return;
1282     }
1283 
1284     SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1285     ScopedContentEntry content(this, &this->cs(), matrix, paint);
1286     if (!content) {
1287         return;
1288     }
1289     if (content.needShape()) {
1290         SkISize dim = device->imageInfo().dimensions();
1291         content.setShape(to_path(SkRect::Make(SkIRect::MakeXYWH(x, y, dim.width(), dim.height()))));
1292     }
1293     if (!content.needSource()) {
1294         return;
1295     }
1296     this->drawFormXObject(pdfDevice->makeFormXObjectFromDevice(), content.stream());
1297 }
1298 
makeSurface(const SkImageInfo & info,const SkSurfaceProps & props)1299 sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1300     return SkSurface::MakeRaster(info, &props);
1301 }
1302 
sort(const SkTHashSet<SkPDFIndirectReference> & src)1303 static std::vector<SkPDFIndirectReference> sort(const SkTHashSet<SkPDFIndirectReference>& src) {
1304     std::vector<SkPDFIndirectReference> dst;
1305     dst.reserve(src.count());
1306     src.foreach([&dst](SkPDFIndirectReference ref) { dst.push_back(ref); } );
1307     std::sort(dst.begin(), dst.end(),
1308             [](SkPDFIndirectReference a, SkPDFIndirectReference b) { return a.fValue < b.fValue; });
1309     return dst;
1310 }
1311 
makeResourceDict()1312 std::unique_ptr<SkPDFDict> SkPDFDevice::makeResourceDict() {
1313     return SkPDFMakeResourceDict(sort(fGraphicStateResources),
1314                                  sort(fShaderResources),
1315                                  sort(fXObjectResources),
1316                                  sort(fFontResources));
1317 }
1318 
content()1319 std::unique_ptr<SkStreamAsset> SkPDFDevice::content() {
1320     if (fActiveStackState.fContentStream) {
1321         fActiveStackState.drainStack();
1322         fActiveStackState = GraphicStackState();
1323     }
1324     if (fContent.bytesWritten() == 0) {
1325         return skstd::make_unique<SkMemoryStream>();
1326     }
1327     SkDynamicMemoryWStream buffer;
1328     if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1329         append_transform(fInitialTransform, &buffer);
1330     }
1331     if (fNeedsExtraSave) {
1332         buffer.writeText("q\n");
1333     }
1334     fContent.writeToAndReset(&buffer);
1335     if (fNeedsExtraSave) {
1336         buffer.writeText("Q\n");
1337     }
1338     fNeedsExtraSave = false;
1339     return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1340 }
1341 
1342 /* Draws an inverse filled path by using Path Ops to compute the positive
1343  * inverse using the current clip as the inverse bounds.
1344  * Return true if this was an inverse path and was properly handled,
1345  * otherwise returns false and the normal drawing routine should continue,
1346  * either as a (incorrect) fallback or because the path was not inverse
1347  * in the first place.
1348  */
handleInversePath(const SkPath & origPath,const SkPaint & paint,bool pathIsMutable)1349 bool SkPDFDevice::handleInversePath(const SkPath& origPath,
1350                                     const SkPaint& paint,
1351                                     bool pathIsMutable) {
1352     if (!origPath.isInverseFillType()) {
1353         return false;
1354     }
1355 
1356     if (this->hasEmptyClip()) {
1357         return false;
1358     }
1359 
1360     SkPath modifiedPath;
1361     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1362     SkPaint noInversePaint(paint);
1363 
1364     // Merge stroking operations into final path.
1365     if (SkPaint::kStroke_Style == paint.getStyle() ||
1366         SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1367         bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1368         if (doFillPath) {
1369             noInversePaint.setStyle(SkPaint::kFill_Style);
1370             noInversePaint.setStrokeWidth(0);
1371             pathPtr = &modifiedPath;
1372         } else {
1373             // To be consistent with the raster output, hairline strokes
1374             // are rendered as non-inverted.
1375             modifiedPath.toggleInverseFillType();
1376             this->drawPath(modifiedPath, paint, true);
1377             return true;
1378         }
1379     }
1380 
1381     // Get bounds of clip in current transform space
1382     // (clip bounds are given in device space).
1383     SkMatrix transformInverse;
1384     SkMatrix totalMatrix = this->ctm();
1385 
1386     if (!totalMatrix.invert(&transformInverse)) {
1387         return false;
1388     }
1389     SkRect bounds = this->cs().bounds(this->bounds());
1390     transformInverse.mapRect(&bounds);
1391 
1392     // Extend the bounds by the line width (plus some padding)
1393     // so the edge doesn't cause a visible stroke.
1394     bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1395                   paint.getStrokeWidth() + SK_Scalar1);
1396 
1397     if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1398         return false;
1399     }
1400 
1401     this->drawPath(modifiedPath, noInversePaint, true);
1402     return true;
1403 }
1404 
getAnnotations()1405 std::unique_ptr<SkPDFArray> SkPDFDevice::getAnnotations() {
1406     std::unique_ptr<SkPDFArray> array;
1407     size_t count = fLinkToURLs.size() + fLinkToDestinations.size();
1408     if (0 == count) {
1409         return array;
1410     }
1411     array = SkPDFMakeArray();
1412     array->reserve(count);
1413     for (const RectWithData& rectWithURL : fLinkToURLs) {
1414         SkRect r;
1415         fInitialTransform.mapRect(&r, rectWithURL.rect);
1416         array->appendRef(fDocument->emit(*create_link_to_url(rectWithURL.data.get(), r)));
1417     }
1418     for (const RectWithData& linkToDestination : fLinkToDestinations) {
1419         SkRect r;
1420         fInitialTransform.mapRect(&r, linkToDestination.rect);
1421         array->appendRef(
1422                 fDocument->emit(*create_link_named_dest(linkToDestination.data.get(), r)));
1423     }
1424     return array;
1425 }
1426 
appendDestinations(SkPDFDict * dict,SkPDFIndirectReference page) const1427 void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFIndirectReference page) const {
1428     for (const NamedDestination& dest : fNamedDestinations) {
1429         SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
1430         auto pdfDest = SkPDFMakeArray();
1431         pdfDest->reserve(5);
1432         pdfDest->appendRef(page);
1433         pdfDest->appendName("XYZ");
1434         pdfDest->appendScalar(p.x());
1435         pdfDest->appendScalar(p.y());
1436         pdfDest->appendInt(0);  // Leave zoom unchanged
1437         dict->insertObject(SkString(static_cast<const char*>(dest.nameData->data())),
1438                            std::move(pdfDest));
1439     }
1440 }
1441 
makeFormXObjectFromDevice(bool alpha)1442 SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
1443     SkMatrix inverseTransform = SkMatrix::I();
1444     if (!fInitialTransform.isIdentity()) {
1445         if (!fInitialTransform.invert(&inverseTransform)) {
1446             SkDEBUGFAIL("Layer initial transform should be invertible.");
1447             inverseTransform.reset();
1448         }
1449     }
1450     const char* colorSpace = alpha ? "DeviceGray" : nullptr;
1451 
1452     SkPDFIndirectReference xobject =
1453         SkPDFMakeFormXObject(fDocument, this->content(),
1454                              SkPDFMakeArray(0, 0, this->width(), this->height()),
1455                              this->makeResourceDict(), inverseTransform, colorSpace);
1456     // We always draw the form xobjects that we create back into the device, so
1457     // we simply preserve the font usage instead of pulling it out and merging
1458     // it back in later.
1459     this->reset();
1460     return xobject;
1461 }
1462 
drawFormXObjectWithMask(SkPDFIndirectReference xObject,SkPDFIndirectReference sMask,SkBlendMode mode,bool invertClip)1463 void SkPDFDevice::drawFormXObjectWithMask(SkPDFIndirectReference xObject,
1464                                           SkPDFIndirectReference sMask,
1465                                           SkBlendMode mode,
1466                                           bool invertClip) {
1467     SkASSERT(sMask);
1468     SkPaint paint;
1469     paint.setBlendMode(mode);
1470     ScopedContentEntry content(this, nullptr, SkMatrix::I(), paint);
1471     if (!content) {
1472         return;
1473     }
1474     this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
1475             sMask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode,
1476             fDocument), content.stream());
1477     this->drawFormXObject(xObject, content.stream());
1478     this->clearMaskOnGraphicState(content.stream());
1479 }
1480 
1481 
treat_as_regular_pdf_blend_mode(SkBlendMode blendMode)1482 static bool treat_as_regular_pdf_blend_mode(SkBlendMode blendMode) {
1483     return nullptr != SkPDFUtils::BlendModeName(blendMode);
1484 }
1485 
populate_graphic_state_entry_from_paint(SkPDFDocument * doc,const SkMatrix & matrix,const SkClipStack * clipStack,SkIRect deviceBounds,const SkPaint & paint,const SkMatrix & initialTransform,SkScalar textScale,SkPDFDevice::GraphicStateEntry * entry,SkTHashSet<SkPDFIndirectReference> * shaderResources,SkTHashSet<SkPDFIndirectReference> * graphicStateResources)1486 static void populate_graphic_state_entry_from_paint(
1487         SkPDFDocument* doc,
1488         const SkMatrix& matrix,
1489         const SkClipStack* clipStack,
1490         SkIRect deviceBounds,
1491         const SkPaint& paint,
1492         const SkMatrix& initialTransform,
1493         SkScalar textScale,
1494         SkPDFDevice::GraphicStateEntry* entry,
1495         SkTHashSet<SkPDFIndirectReference>* shaderResources,
1496         SkTHashSet<SkPDFIndirectReference>* graphicStateResources) {
1497     NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1498     NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1499     NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
1500 
1501     entry->fMatrix = matrix;
1502     entry->fClipStackGenID = clipStack ? clipStack->getTopmostGenID()
1503                                        : SkClipStack::kWideOpenGenID;
1504     SkColor4f color = paint.getColor4f();
1505     entry->fColor = {color.fR, color.fG, color.fB, 1};
1506     entry->fShaderIndex = -1;
1507 
1508     // PDF treats a shader as a color, so we only set one or the other.
1509     SkShader* shader = paint.getShader();
1510     if (shader) {
1511         if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1512             // We don't have to set a shader just for a color.
1513             SkShader::GradientInfo gradientInfo;
1514             SkColor gradientColor = SK_ColorBLACK;
1515             gradientInfo.fColors = &gradientColor;
1516             gradientInfo.fColorOffsets = nullptr;
1517             gradientInfo.fColorCount = 1;
1518             SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1519             color = SkColor4f::FromColor(gradientColor);
1520             entry->fColor ={color.fR, color.fG, color.fB, 1};
1521 
1522         } else {
1523             // PDF positions patterns relative to the initial transform, so
1524             // we need to apply the current transform to the shader parameters.
1525             SkMatrix transform = matrix;
1526             transform.postConcat(initialTransform);
1527 
1528             // PDF doesn't support kClamp_TileMode, so we simulate it by making
1529             // a pattern the size of the current clip.
1530             SkRect clipStackBounds = clipStack ? clipStack->bounds(deviceBounds)
1531                                                : SkRect::Make(deviceBounds);
1532 
1533             // We need to apply the initial transform to bounds in order to get
1534             // bounds in a consistent coordinate system.
1535             initialTransform.mapRect(&clipStackBounds);
1536             SkIRect bounds;
1537             clipStackBounds.roundOut(&bounds);
1538 
1539             SkPDFIndirectReference pdfShader
1540                 = SkPDFMakeShader(doc, shader, transform, bounds, paint.getColor());
1541 
1542             if (pdfShader) {
1543                 // pdfShader has been canonicalized so we can directly compare pointers.
1544                 entry->fShaderIndex = add_resource(*shaderResources, pdfShader);
1545             }
1546         }
1547     }
1548 
1549     SkPDFIndirectReference newGraphicState;
1550     if (color == paint.getColor4f()) {
1551         newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, paint);
1552     } else {
1553         SkPaint newPaint = paint;
1554         newPaint.setColor4f(color, nullptr);
1555         newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, newPaint);
1556     }
1557     entry->fGraphicStateIndex = add_resource(*graphicStateResources, newGraphicState);
1558     entry->fTextScaleX = textScale;
1559 }
1560 
setUpContentEntry(const SkClipStack * clipStack,const SkMatrix & matrix,const SkPaint & paint,SkScalar textScale,SkPDFIndirectReference * dst)1561 SkDynamicMemoryWStream* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1562                                                        const SkMatrix& matrix,
1563                                                        const SkPaint& paint,
1564                                                        SkScalar textScale,
1565                                                        SkPDFIndirectReference* dst) {
1566     SkASSERT(!*dst);
1567     SkBlendMode blendMode = paint.getBlendMode();
1568 
1569     // Dst xfer mode doesn't draw source at all.
1570     if (blendMode == SkBlendMode::kDst) {
1571         return nullptr;
1572     }
1573 
1574     // For the following modes, we want to handle source and destination
1575     // separately, so make an object of what's already there.
1576     if (!treat_as_regular_pdf_blend_mode(blendMode) && blendMode != SkBlendMode::kDstOver) {
1577         if (!isContentEmpty()) {
1578             *dst = this->makeFormXObjectFromDevice();
1579             SkASSERT(isContentEmpty());
1580         } else if (blendMode != SkBlendMode::kSrc &&
1581                    blendMode != SkBlendMode::kSrcOut) {
1582             // Except for Src and SrcOut, if there isn't anything already there,
1583             // then we're done.
1584             return nullptr;
1585         }
1586     }
1587     // TODO(vandebo): Figure out how/if we can handle the following modes:
1588     // Xor, Plus.  For now, we treat them as SrcOver/Normal.
1589 
1590     if (treat_as_regular_pdf_blend_mode(blendMode)) {
1591         if (!fActiveStackState.fContentStream) {
1592             if (fContent.bytesWritten() != 0) {
1593                 fContent.writeText("Q\nq\n");
1594                 fNeedsExtraSave = true;
1595             }
1596             fActiveStackState = GraphicStackState(&fContent);
1597         } else {
1598             SkASSERT(fActiveStackState.fContentStream = &fContent);
1599         }
1600     } else {
1601         fActiveStackState.drainStack();
1602         fActiveStackState = GraphicStackState(&fContentBuffer);
1603     }
1604     SkASSERT(fActiveStackState.fContentStream);
1605     GraphicStateEntry entry;
1606     populate_graphic_state_entry_from_paint(
1607             fDocument,
1608             matrix,
1609             clipStack,
1610             this->bounds(),
1611             paint,
1612             fInitialTransform,
1613             textScale,
1614             &entry,
1615             &fShaderResources,
1616             &fGraphicStateResources);
1617     fActiveStackState.updateClip(clipStack, this->bounds());
1618     fActiveStackState.updateMatrix(entry.fMatrix);
1619     fActiveStackState.updateDrawingState(entry);
1620 
1621     return fActiveStackState.fContentStream;
1622 }
1623 
finishContentEntry(const SkClipStack * clipStack,SkBlendMode blendMode,SkPDFIndirectReference dst,SkPath * shape)1624 void SkPDFDevice::finishContentEntry(const SkClipStack* clipStack,
1625                                      SkBlendMode blendMode,
1626                                      SkPDFIndirectReference dst,
1627                                      SkPath* shape) {
1628     SkASSERT(blendMode != SkBlendMode::kDst);
1629     if (treat_as_regular_pdf_blend_mode(blendMode)) {
1630         SkASSERT(!dst);
1631         return;
1632     }
1633 
1634     SkASSERT(fActiveStackState.fContentStream);
1635 
1636     fActiveStackState.drainStack();
1637     fActiveStackState = GraphicStackState();
1638 
1639     if (blendMode == SkBlendMode::kDstOver) {
1640         SkASSERT(!dst);
1641         if (fContentBuffer.bytesWritten() != 0) {
1642             if (fContent.bytesWritten() != 0) {
1643                 fContentBuffer.writeText("Q\nq\n");
1644                 fNeedsExtraSave = true;
1645             }
1646             fContentBuffer.prependToAndReset(&fContent);
1647             SkASSERT(fContentBuffer.bytesWritten() == 0);
1648         }
1649         return;
1650     }
1651     if (fContentBuffer.bytesWritten() != 0) {
1652         if (fContent.bytesWritten() != 0) {
1653             fContent.writeText("Q\nq\n");
1654             fNeedsExtraSave = true;
1655         }
1656         fContentBuffer.writeToAndReset(&fContent);
1657         SkASSERT(fContentBuffer.bytesWritten() == 0);
1658     }
1659 
1660     if (!dst) {
1661         SkASSERT(blendMode == SkBlendMode::kSrc ||
1662                  blendMode == SkBlendMode::kSrcOut);
1663         return;
1664     }
1665 
1666     SkASSERT(dst);
1667     // Changing the current content into a form-xobject will destroy the clip
1668     // objects which is fine since the xobject will already be clipped. However
1669     // if source has shape, we need to clip it too, so a copy of the clip is
1670     // saved.
1671 
1672     SkPaint stockPaint;
1673 
1674     SkPDFIndirectReference srcFormXObject;
1675     if (this->isContentEmpty()) {
1676         // If nothing was drawn and there's no shape, then the draw was a
1677         // no-op, but dst needs to be restored for that to be true.
1678         // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1679         // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1680         // reduces to Dst.
1681         if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1682                 blendMode == SkBlendMode::kSrcATop) {
1683             ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
1684             this->drawFormXObject(dst, content.stream());
1685             return;
1686         } else {
1687             blendMode = SkBlendMode::kClear;
1688         }
1689     } else {
1690         srcFormXObject = this->makeFormXObjectFromDevice();
1691     }
1692 
1693     // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1694     // without alpha.
1695     if (blendMode == SkBlendMode::kSrcATop) {
1696         // TODO(vandebo): In order to properly support SrcATop we have to track
1697         // the shape of what's been drawn at all times. It's the intersection of
1698         // the non-transparent parts of the device and the outlines (shape) of
1699         // all images and devices drawn.
1700         this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, true);
1701     } else {
1702         if (shape != nullptr) {
1703             // Draw shape into a form-xobject.
1704             SkPaint filledPaint;
1705             filledPaint.setColor(SK_ColorBLACK);
1706             filledPaint.setStyle(SkPaint::kFill_Style);
1707             SkClipStack empty;
1708             SkPDFDevice shapeDev(this->size(), fDocument, fInitialTransform);
1709             shapeDev.internalDrawPath(clipStack ? *clipStack : empty,
1710                                       SkMatrix::I(), *shape, filledPaint, true);
1711             this->drawFormXObjectWithMask(dst, shapeDev.makeFormXObjectFromDevice(),
1712                                           SkBlendMode::kSrcOver, true);
1713         } else {
1714             this->drawFormXObjectWithMask(dst, srcFormXObject, SkBlendMode::kSrcOver, true);
1715         }
1716     }
1717 
1718     if (blendMode == SkBlendMode::kClear) {
1719         return;
1720     } else if (blendMode == SkBlendMode::kSrc ||
1721             blendMode == SkBlendMode::kDstATop) {
1722         ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
1723         if (content) {
1724             this->drawFormXObject(srcFormXObject, content.stream());
1725         }
1726         if (blendMode == SkBlendMode::kSrc) {
1727             return;
1728         }
1729     } else if (blendMode == SkBlendMode::kSrcATop) {
1730         ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
1731         if (content) {
1732             this->drawFormXObject(dst, content.stream());
1733         }
1734     }
1735 
1736     SkASSERT(blendMode == SkBlendMode::kSrcIn   ||
1737              blendMode == SkBlendMode::kDstIn   ||
1738              blendMode == SkBlendMode::kSrcOut  ||
1739              blendMode == SkBlendMode::kDstOut  ||
1740              blendMode == SkBlendMode::kSrcATop ||
1741              blendMode == SkBlendMode::kDstATop ||
1742              blendMode == SkBlendMode::kModulate);
1743 
1744     if (blendMode == SkBlendMode::kSrcIn ||
1745             blendMode == SkBlendMode::kSrcOut ||
1746             blendMode == SkBlendMode::kSrcATop) {
1747         this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver,
1748                                       blendMode == SkBlendMode::kSrcOut);
1749         return;
1750     } else {
1751         SkBlendMode mode = SkBlendMode::kSrcOver;
1752         if (blendMode == SkBlendMode::kModulate) {
1753             this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, false);
1754             mode = SkBlendMode::kMultiply;
1755         }
1756         this->drawFormXObjectWithMask(dst, srcFormXObject, mode, blendMode == SkBlendMode::kDstOut);
1757         return;
1758     }
1759 }
1760 
isContentEmpty()1761 bool SkPDFDevice::isContentEmpty() {
1762     return fContent.bytesWritten() == 0 && fContentBuffer.bytesWritten() == 0;
1763 }
1764 
rect_to_size(const SkRect & r)1765 static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
1766 
color_filter(const SkImage * image,SkColorFilter * colorFilter)1767 static sk_sp<SkImage> color_filter(const SkImage* image,
1768                                    SkColorFilter* colorFilter) {
1769     auto surface =
1770         SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
1771     SkASSERT(surface);
1772     SkCanvas* canvas = surface->getCanvas();
1773     canvas->clear(SK_ColorTRANSPARENT);
1774     SkPaint paint;
1775     paint.setColorFilter(sk_ref_sp(colorFilter));
1776     canvas->drawImage(image, 0, 0, &paint);
1777     return surface->makeImageSnapshot();
1778 }
1779 
1780 ////////////////////////////////////////////////////////////////////////////////
1781 
is_integer(SkScalar x)1782 static bool is_integer(SkScalar x) {
1783     return x == SkScalarTruncToScalar(x);
1784 }
1785 
is_integral(const SkRect & r)1786 static bool is_integral(const SkRect& r) {
1787     return is_integer(r.left()) &&
1788            is_integer(r.top()) &&
1789            is_integer(r.right()) &&
1790            is_integer(r.bottom());
1791 }
1792 
internalDrawImageRect(SkKeyedImage imageSubset,const SkRect * src,const SkRect & dst,const SkPaint & srcPaint,const SkMatrix & ctm)1793 void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
1794                                         const SkRect* src,
1795                                         const SkRect& dst,
1796                                         const SkPaint& srcPaint,
1797                                         const SkMatrix& ctm) {
1798     if (this->hasEmptyClip()) {
1799         return;
1800     }
1801     if (!imageSubset) {
1802         return;
1803     }
1804 
1805     // First, figure out the src->dst transform and subset the image if needed.
1806     SkIRect bounds = imageSubset.image()->bounds();
1807     SkRect srcRect = src ? *src : SkRect::Make(bounds);
1808     SkMatrix transform;
1809     transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
1810     if (src && *src != SkRect::Make(bounds)) {
1811         if (!srcRect.intersect(SkRect::Make(bounds))) {
1812             return;
1813         }
1814         srcRect.roundOut(&bounds);
1815         transform.preTranslate(SkIntToScalar(bounds.x()),
1816                                SkIntToScalar(bounds.y()));
1817         if (bounds != imageSubset.image()->bounds()) {
1818             imageSubset = imageSubset.subset(bounds);
1819         }
1820         if (!imageSubset) {
1821             return;
1822         }
1823     }
1824 
1825     // If the image is opaque and the paint's alpha is too, replace
1826     // kSrc blendmode with kSrcOver.
1827     SkPaint paint = srcPaint;
1828     if (imageSubset.image()->isOpaque()) {
1829         replace_srcmode_on_opaque_paint(&paint);
1830     }
1831 
1832     // Alpha-only images need to get their color from the shader, before
1833     // applying the colorfilter.
1834     if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
1835         // must blend alpha image and shader before applying colorfilter.
1836         auto surface =
1837             SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
1838         SkCanvas* canvas = surface->getCanvas();
1839         SkPaint tmpPaint;
1840         // In the case of alpha images with shaders, the shader's coordinate
1841         // system is the image's coordiantes.
1842         tmpPaint.setShader(sk_ref_sp(paint.getShader()));
1843         tmpPaint.setColor4f(paint.getColor4f(), nullptr);
1844         canvas->clear(0x00000000);
1845         canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
1846         paint.setShader(nullptr);
1847         imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1848         SkASSERT(!imageSubset.image()->isAlphaOnly());
1849     }
1850 
1851     if (imageSubset.image()->isAlphaOnly()) {
1852         // The ColorFilter applies to the paint color/shader, not the alpha layer.
1853         SkASSERT(nullptr == paint.getColorFilter());
1854 
1855         sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
1856         if (!mask) {
1857             return;
1858         }
1859         // PDF doesn't seem to allow masking vector graphics with an Image XObject.
1860         // Must mask with a Form XObject.
1861         sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
1862         {
1863             SkCanvas canvas(maskDevice);
1864             if (paint.getMaskFilter()) {
1865                 // This clip prevents the mask image shader from covering
1866                 // entire device if unnecessary.
1867                 canvas.clipRect(this->cs().bounds(this->bounds()));
1868                 canvas.concat(ctm);
1869                 SkPaint tmpPaint;
1870                 tmpPaint.setShader(mask->makeShader(&transform));
1871                 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
1872                 canvas.drawRect(dst, tmpPaint);
1873             } else {
1874                 canvas.concat(ctm);
1875                 if (src && !is_integral(*src)) {
1876                     canvas.clipRect(dst);
1877                 }
1878                 canvas.concat(transform);
1879                 canvas.drawImage(mask, 0, 0);
1880             }
1881         }
1882         if (!ctm.isIdentity() && paint.getShader()) {
1883             transform_shader(&paint, ctm); // Since we are using identity matrix.
1884         }
1885         ScopedContentEntry content(this, &this->cs(), SkMatrix::I(), paint);
1886         if (!content) {
1887             return;
1888         }
1889         this->addSMaskGraphicState(std::move(maskDevice), content.stream());
1890         SkPDFUtils::AppendRectangle(SkRect::Make(this->size()), content.stream());
1891         SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
1892         this->clearMaskOnGraphicState(content.stream());
1893         return;
1894     }
1895     if (paint.getMaskFilter()) {
1896         paint.setShader(imageSubset.image()->makeShader(&transform));
1897         SkPath path = to_path(dst); // handles non-integral clipping.
1898         this->internalDrawPath(this->cs(), this->ctm(), path, paint, true);
1899         return;
1900     }
1901     transform.postConcat(ctm);
1902 
1903     bool needToRestore = false;
1904     if (src && !is_integral(*src)) {
1905         // Need sub-pixel clipping to fix https://bug.skia.org/4374
1906         this->cs().save();
1907         this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
1908         needToRestore = true;
1909     }
1910     SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
1911 
1912     SkMatrix matrix = transform;
1913 
1914     // Rasterize the bitmap using perspective in a new bitmap.
1915     if (transform.hasPerspective()) {
1916         // Transform the bitmap in the new space, without taking into
1917         // account the initial transform.
1918         SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
1919         SkPath perspectiveOutline = to_path(imageBounds);
1920         perspectiveOutline.transform(transform);
1921 
1922         // TODO(edisonn): perf - use current clip too.
1923         // Retrieve the bounds of the new shape.
1924         SkRect bounds = perspectiveOutline.getBounds();
1925 
1926         // Transform the bitmap in the new space, taking into
1927         // account the initial transform.
1928         SkMatrix total = transform;
1929         total.postConcat(fInitialTransform);
1930 
1931         SkPath physicalPerspectiveOutline = to_path(imageBounds);
1932         physicalPerspectiveOutline.transform(total);
1933 
1934         SkRect physicalPerspectiveBounds =
1935                 physicalPerspectiveOutline.getBounds();
1936         SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
1937         SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
1938 
1939         // TODO(edisonn): A better approach would be to use a bitmap shader
1940         // (in clamp mode) and draw a rect over the entire bounding box. Then
1941         // intersect perspectiveOutline to the clip. That will avoid introducing
1942         // alpha to the image while still giving good behavior at the edge of
1943         // the image.  Avoiding alpha will reduce the pdf size and generation
1944         // CPU time some.
1945 
1946         SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
1947 
1948         auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
1949         if (!surface) {
1950             return;
1951         }
1952         SkCanvas* canvas = surface->getCanvas();
1953         canvas->clear(SK_ColorTRANSPARENT);
1954 
1955         SkScalar deltaX = bounds.left();
1956         SkScalar deltaY = bounds.top();
1957 
1958         SkMatrix offsetMatrix = transform;
1959         offsetMatrix.postTranslate(-deltaX, -deltaY);
1960         offsetMatrix.postScale(scaleX, scaleY);
1961 
1962         // Translate the draw in the new canvas, so we perfectly fit the
1963         // shape in the bitmap.
1964         canvas->setMatrix(offsetMatrix);
1965         canvas->drawImage(imageSubset.image(), 0, 0);
1966         // Make sure the final bits are in the bitmap.
1967         canvas->flush();
1968 
1969         // In the new space, we use the identity matrix translated
1970         // and scaled to reflect DPI.
1971         matrix.setScale(1 / scaleX, 1 / scaleY);
1972         matrix.postTranslate(deltaX, deltaY);
1973 
1974         imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1975         if (!imageSubset) {
1976             return;
1977         }
1978     }
1979 
1980     SkMatrix scaled;
1981     // Adjust for origin flip.
1982     scaled.setScale(SK_Scalar1, -SK_Scalar1);
1983     scaled.postTranslate(0, SK_Scalar1);
1984     // Scale the image up from 1x1 to WxH.
1985     SkIRect subset = imageSubset.image()->bounds();
1986     scaled.postScale(SkIntToScalar(subset.width()),
1987                      SkIntToScalar(subset.height()));
1988     scaled.postConcat(matrix);
1989     ScopedContentEntry content(this, &this->cs(), scaled, paint);
1990     if (!content) {
1991         return;
1992     }
1993     if (content.needShape()) {
1994         SkPath shape = to_path(SkRect::Make(subset));
1995         shape.transform(matrix);
1996         content.setShape(shape);
1997     }
1998     if (!content.needSource()) {
1999         return;
2000     }
2001 
2002     if (SkColorFilter* colorFilter = paint.getColorFilter()) {
2003         sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2004         imageSubset = SkKeyedImage(std::move(img));
2005         if (!imageSubset) {
2006             return;
2007         }
2008         // TODO(halcanary): de-dupe this by caching filtered images.
2009         // (maybe in the resource cache?)
2010     }
2011 
2012     SkBitmapKey key = imageSubset.key();
2013     SkPDFIndirectReference* pdfimagePtr = fDocument->fPDFBitmapMap.find(key);
2014     SkPDFIndirectReference pdfimage = pdfimagePtr ? *pdfimagePtr : SkPDFIndirectReference();
2015     if (!pdfimagePtr) {
2016         SkASSERT(imageSubset);
2017         pdfimage = SkPDFSerializeImage(imageSubset.image().get(), fDocument,
2018                                        fDocument->metadata().fEncodingQuality);
2019         SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
2020         fDocument->fPDFBitmapMap.set(key, pdfimage);
2021     }
2022     SkASSERT(pdfimage != SkPDFIndirectReference());
2023     this->drawFormXObject(pdfimage, content.stream());
2024 }
2025 
2026 ///////////////////////////////////////////////////////////////////////////////////////////////////
2027 
2028 #include "SkSpecialImage.h"
2029 #include "SkImageFilter.h"
2030 
drawSpecial(SkSpecialImage * srcImg,int x,int y,const SkPaint & paint,SkImage * clipImage,const SkMatrix & clipMatrix)2031 void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2032                               SkImage* clipImage, const SkMatrix& clipMatrix) {
2033     if (this->hasEmptyClip()) {
2034         return;
2035     }
2036     SkASSERT(!srcImg->isTextureBacked());
2037 
2038     //TODO: clipImage support
2039 
2040     SkBitmap resultBM;
2041 
2042     SkImageFilter* filter = paint.getImageFilter();
2043     if (filter) {
2044         SkIPoint offset = SkIPoint::Make(0, 0);
2045         SkMatrix matrix = this->ctm();
2046         matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
2047         const SkIRect clipBounds =
2048             this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
2049         sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
2050         // TODO: Should PDF be operating in a specified color type/space? For now, run the filter
2051         // in the same color space as the source (this is different from all other backends).
2052         SkImageFilter::OutputProperties outputProperties(kN32_SkColorType, srcImg->getColorSpace());
2053         SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
2054 
2055         sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2056         if (resultImg) {
2057             SkPaint tmpUnfiltered(paint);
2058             tmpUnfiltered.setImageFilter(nullptr);
2059             if (resultImg->getROPixels(&resultBM)) {
2060                 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2061             }
2062         }
2063     } else {
2064         if (srcImg->getROPixels(&resultBM)) {
2065             this->drawSprite(resultBM, x, y, paint);
2066         }
2067     }
2068 }
2069 
makeSpecial(const SkBitmap & bitmap)2070 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2071     return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2072 }
2073 
makeSpecial(const SkImage * image)2074 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
2075     return SkSpecialImage::MakeFromImage(nullptr, image->bounds(), image->makeNonTextureImage());
2076 }
2077 
snapSpecial()2078 sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
2079     return nullptr;
2080 }
2081 
getImageFilterCache()2082 SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2083     // We always return a transient cache, so it is freed after each
2084     // filter traversal.
2085     return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2086 }
2087