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