• 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(*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(const SkGlyphRunList & glyphRunList,const SkPaint & paint)959 void SkPDFDevice::onDrawGlyphRunList(const SkGlyphRunList& glyphRunList, const SkPaint& paint) {
960     SkASSERT(!glyphRunList.hasRSXForm());
961     for (const SkGlyphRun& glyphRun : glyphRunList) {
962         this->internalDrawGlyphRun(glyphRun, glyphRunList.origin(), paint);
963     }
964 }
965 
drawVertices(const SkVertices *,SkBlendMode,const SkPaint &)966 void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
967     if (this->hasEmptyClip()) {
968         return;
969     }
970     // TODO: implement drawVertices
971 }
972 
drawFormXObject(SkPDFIndirectReference xObject,SkDynamicMemoryWStream * content)973 void SkPDFDevice::drawFormXObject(SkPDFIndirectReference xObject, SkDynamicMemoryWStream* content) {
974     ScopedOutputMarkedContentTags mark(fNodeId, fDocument, content);
975 
976     SkASSERT(xObject);
977     SkPDFWriteResourceName(content, SkPDFResourceType::kXObject,
978                            add_resource(fXObjectResources, xObject));
979     content->writeText(" Do\n");
980 }
981 
makeSurface(const SkImageInfo & info,const SkSurfaceProps & props)982 sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
983     return SkSurface::MakeRaster(info, &props);
984 }
985 
sort(const SkTHashSet<SkPDFIndirectReference> & src)986 static std::vector<SkPDFIndirectReference> sort(const SkTHashSet<SkPDFIndirectReference>& src) {
987     std::vector<SkPDFIndirectReference> dst;
988     dst.reserve(src.count());
989     for (SkPDFIndirectReference ref : src) {
990         dst.push_back(ref);
991     }
992     std::sort(dst.begin(), dst.end(),
993             [](SkPDFIndirectReference a, SkPDFIndirectReference b) { return a.fValue < b.fValue; });
994     return dst;
995 }
996 
makeResourceDict()997 std::unique_ptr<SkPDFDict> SkPDFDevice::makeResourceDict() {
998     return SkPDFMakeResourceDict(sort(fGraphicStateResources),
999                                  sort(fShaderResources),
1000                                  sort(fXObjectResources),
1001                                  sort(fFontResources));
1002 }
1003 
content()1004 std::unique_ptr<SkStreamAsset> SkPDFDevice::content() {
1005     if (fActiveStackState.fContentStream) {
1006         fActiveStackState.drainStack();
1007         fActiveStackState = SkPDFGraphicStackState();
1008     }
1009     if (fContent.bytesWritten() == 0) {
1010         return std::make_unique<SkMemoryStream>();
1011     }
1012     SkDynamicMemoryWStream buffer;
1013     if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1014         SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
1015     }
1016     if (fNeedsExtraSave) {
1017         buffer.writeText("q\n");
1018     }
1019     fContent.writeToAndReset(&buffer);
1020     if (fNeedsExtraSave) {
1021         buffer.writeText("Q\n");
1022     }
1023     fNeedsExtraSave = false;
1024     return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1025 }
1026 
1027 /* Draws an inverse filled path by using Path Ops to compute the positive
1028  * inverse using the current clip as the inverse bounds.
1029  * Return true if this was an inverse path and was properly handled,
1030  * otherwise returns false and the normal drawing routine should continue,
1031  * either as a (incorrect) fallback or because the path was not inverse
1032  * in the first place.
1033  */
handleInversePath(const SkPath & origPath,const SkPaint & paint,bool pathIsMutable)1034 bool SkPDFDevice::handleInversePath(const SkPath& origPath,
1035                                     const SkPaint& paint,
1036                                     bool pathIsMutable) {
1037     if (!origPath.isInverseFillType()) {
1038         return false;
1039     }
1040 
1041     if (this->hasEmptyClip()) {
1042         return false;
1043     }
1044 
1045     SkPath modifiedPath;
1046     SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1047     SkPaint noInversePaint(paint);
1048 
1049     // Merge stroking operations into final path.
1050     if (SkPaint::kStroke_Style == paint.getStyle() ||
1051         SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1052         bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1053         if (doFillPath) {
1054             noInversePaint.setStyle(SkPaint::kFill_Style);
1055             noInversePaint.setStrokeWidth(0);
1056             pathPtr = &modifiedPath;
1057         } else {
1058             // To be consistent with the raster output, hairline strokes
1059             // are rendered as non-inverted.
1060             modifiedPath.toggleInverseFillType();
1061             this->internalDrawPath(this->cs(), this->localToDevice(), modifiedPath, paint, true);
1062             return true;
1063         }
1064     }
1065 
1066     // Get bounds of clip in current transform space
1067     // (clip bounds are given in device space).
1068     SkMatrix transformInverse;
1069     SkMatrix totalMatrix = this->localToDevice();
1070 
1071     if (!totalMatrix.invert(&transformInverse)) {
1072         return false;
1073     }
1074     SkRect bounds = this->cs().bounds(this->bounds());
1075     transformInverse.mapRect(&bounds);
1076 
1077     // Extend the bounds by the line width (plus some padding)
1078     // so the edge doesn't cause a visible stroke.
1079     bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1080                   paint.getStrokeWidth() + SK_Scalar1);
1081 
1082     if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1083         return false;
1084     }
1085 
1086     this->internalDrawPath(this->cs(), this->localToDevice(), modifiedPath, noInversePaint, true);
1087     return true;
1088 }
1089 
makeFormXObjectFromDevice(SkIRect bounds,bool alpha)1090 SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(SkIRect bounds, bool alpha) {
1091     SkMatrix inverseTransform = SkMatrix::I();
1092     if (!fInitialTransform.isIdentity()) {
1093         if (!fInitialTransform.invert(&inverseTransform)) {
1094             SkDEBUGFAIL("Layer initial transform should be invertible.");
1095             inverseTransform.reset();
1096         }
1097     }
1098     const char* colorSpace = alpha ? "DeviceGray" : nullptr;
1099 
1100     SkPDFIndirectReference xobject =
1101         SkPDFMakeFormXObject(fDocument, this->content(),
1102                              SkPDFMakeArray(bounds.left(), bounds.top(),
1103                                             bounds.right(), bounds.bottom()),
1104                              this->makeResourceDict(), inverseTransform, colorSpace);
1105     // We always draw the form xobjects that we create back into the device, so
1106     // we simply preserve the font usage instead of pulling it out and merging
1107     // it back in later.
1108     this->reset();
1109     return xobject;
1110 }
1111 
makeFormXObjectFromDevice(bool alpha)1112 SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
1113     return this->makeFormXObjectFromDevice(SkIRect{0, 0, this->width(), this->height()}, alpha);
1114 }
1115 
drawFormXObjectWithMask(SkPDFIndirectReference xObject,SkPDFIndirectReference sMask,SkBlendMode mode,bool invertClip)1116 void SkPDFDevice::drawFormXObjectWithMask(SkPDFIndirectReference xObject,
1117                                           SkPDFIndirectReference sMask,
1118                                           SkBlendMode mode,
1119                                           bool invertClip) {
1120     SkASSERT(sMask);
1121     SkPaint paint;
1122     paint.setBlendMode(mode);
1123     ScopedContentEntry content(this, nullptr, SkMatrix::I(), paint);
1124     if (!content) {
1125         return;
1126     }
1127     this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
1128             sMask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode,
1129             fDocument), content.stream());
1130     this->drawFormXObject(xObject, content.stream());
1131     this->clearMaskOnGraphicState(content.stream());
1132 }
1133 
1134 
treat_as_regular_pdf_blend_mode(SkBlendMode blendMode)1135 static bool treat_as_regular_pdf_blend_mode(SkBlendMode blendMode) {
1136     return nullptr != SkPDFUtils::BlendModeName(blendMode);
1137 }
1138 
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)1139 static void populate_graphic_state_entry_from_paint(
1140         SkPDFDocument* doc,
1141         const SkMatrix& matrix,
1142         const SkClipStack* clipStack,
1143         SkIRect deviceBounds,
1144         const SkPaint& paint,
1145         const SkMatrix& initialTransform,
1146         SkScalar textScale,
1147         SkPDFGraphicStackState::Entry* entry,
1148         SkTHashSet<SkPDFIndirectReference>* shaderResources,
1149         SkTHashSet<SkPDFIndirectReference>* graphicStateResources) {
1150     NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1151     NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1152     NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
1153 
1154     entry->fMatrix = matrix;
1155     entry->fClipStackGenID = clipStack ? clipStack->getTopmostGenID()
1156                                        : SkClipStack::kWideOpenGenID;
1157     SkColor4f color = paint.getColor4f();
1158     entry->fColor = {color.fR, color.fG, color.fB, 1};
1159     entry->fShaderIndex = -1;
1160 
1161     // PDF treats a shader as a color, so we only set one or the other.
1162     SkShader* shader = paint.getShader();
1163     if (shader) {
1164         // note: we always present the alpha as 1 for the shader, knowing that it will be
1165         //       accounted for when we create our newGraphicsState (below)
1166         if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1167             // We don't have to set a shader just for a color.
1168             SkShader::GradientInfo gradientInfo;
1169             SkColor gradientColor = SK_ColorBLACK;
1170             gradientInfo.fColors = &gradientColor;
1171             gradientInfo.fColorOffsets = nullptr;
1172             gradientInfo.fColorCount = 1;
1173             SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1174             color = SkColor4f::FromColor(gradientColor);
1175             entry->fColor ={color.fR, color.fG, color.fB, 1};
1176 
1177         } else {
1178             // PDF positions patterns relative to the initial transform, so
1179             // we need to apply the current transform to the shader parameters.
1180             SkMatrix transform = matrix;
1181             transform.postConcat(initialTransform);
1182 
1183             // PDF doesn't support kClamp_TileMode, so we simulate it by making
1184             // a pattern the size of the current clip.
1185             SkRect clipStackBounds = clipStack ? clipStack->bounds(deviceBounds)
1186                                                : SkRect::Make(deviceBounds);
1187 
1188             // We need to apply the initial transform to bounds in order to get
1189             // bounds in a consistent coordinate system.
1190             initialTransform.mapRect(&clipStackBounds);
1191             SkIRect bounds;
1192             clipStackBounds.roundOut(&bounds);
1193 
1194             auto c = paint.getColor4f();
1195             SkPDFIndirectReference pdfShader = SkPDFMakeShader(doc, shader, transform, bounds,
1196                                                                {c.fR, c.fG, c.fB, 1.0f});
1197 
1198             if (pdfShader) {
1199                 // pdfShader has been canonicalized so we can directly compare pointers.
1200                 entry->fShaderIndex = add_resource(*shaderResources, pdfShader);
1201             }
1202         }
1203     }
1204 
1205     SkPDFIndirectReference newGraphicState;
1206     if (color == paint.getColor4f()) {
1207         newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, paint);
1208     } else {
1209         SkPaint newPaint = paint;
1210         newPaint.setColor4f(color, nullptr);
1211         newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, newPaint);
1212     }
1213     entry->fGraphicStateIndex = add_resource(*graphicStateResources, newGraphicState);
1214     entry->fTextScaleX = textScale;
1215 }
1216 
setUpContentEntry(const SkClipStack * clipStack,const SkMatrix & matrix,const SkPaint & paint,SkScalar textScale,SkPDFIndirectReference * dst)1217 SkDynamicMemoryWStream* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1218                                                        const SkMatrix& matrix,
1219                                                        const SkPaint& paint,
1220                                                        SkScalar textScale,
1221                                                        SkPDFIndirectReference* dst) {
1222     SkASSERT(!*dst);
1223     SkBlendMode blendMode = paint.getBlendMode_or(SkBlendMode::kSrcOver);
1224 
1225     // Dst xfer mode doesn't draw source at all.
1226     if (blendMode == SkBlendMode::kDst) {
1227         return nullptr;
1228     }
1229 
1230     // For the following modes, we want to handle source and destination
1231     // separately, so make an object of what's already there.
1232     if (!treat_as_regular_pdf_blend_mode(blendMode) && blendMode != SkBlendMode::kDstOver) {
1233         if (!isContentEmpty()) {
1234             *dst = this->makeFormXObjectFromDevice();
1235             SkASSERT(isContentEmpty());
1236         } else if (blendMode != SkBlendMode::kSrc &&
1237                    blendMode != SkBlendMode::kSrcOut) {
1238             // Except for Src and SrcOut, if there isn't anything already there,
1239             // then we're done.
1240             return nullptr;
1241         }
1242     }
1243     // TODO(vandebo): Figure out how/if we can handle the following modes:
1244     // Xor, Plus.  For now, we treat them as SrcOver/Normal.
1245 
1246     if (treat_as_regular_pdf_blend_mode(blendMode)) {
1247         if (!fActiveStackState.fContentStream) {
1248             if (fContent.bytesWritten() != 0) {
1249                 fContent.writeText("Q\nq\n");
1250                 fNeedsExtraSave = true;
1251             }
1252             fActiveStackState = SkPDFGraphicStackState(&fContent);
1253         } else {
1254             SkASSERT(fActiveStackState.fContentStream = &fContent);
1255         }
1256     } else {
1257         fActiveStackState.drainStack();
1258         fActiveStackState = SkPDFGraphicStackState(&fContentBuffer);
1259     }
1260     SkASSERT(fActiveStackState.fContentStream);
1261     SkPDFGraphicStackState::Entry entry;
1262     populate_graphic_state_entry_from_paint(
1263             fDocument,
1264             matrix,
1265             clipStack,
1266             this->bounds(),
1267             paint,
1268             fInitialTransform,
1269             textScale,
1270             &entry,
1271             &fShaderResources,
1272             &fGraphicStateResources);
1273     fActiveStackState.updateClip(clipStack, this->bounds());
1274     fActiveStackState.updateMatrix(entry.fMatrix);
1275     fActiveStackState.updateDrawingState(entry);
1276 
1277     return fActiveStackState.fContentStream;
1278 }
1279 
finishContentEntry(const SkClipStack * clipStack,SkBlendMode blendMode,SkPDFIndirectReference dst,SkPath * shape)1280 void SkPDFDevice::finishContentEntry(const SkClipStack* clipStack,
1281                                      SkBlendMode blendMode,
1282                                      SkPDFIndirectReference dst,
1283                                      SkPath* shape) {
1284     SkASSERT(blendMode != SkBlendMode::kDst);
1285     if (treat_as_regular_pdf_blend_mode(blendMode)) {
1286         SkASSERT(!dst);
1287         return;
1288     }
1289 
1290     SkASSERT(fActiveStackState.fContentStream);
1291 
1292     fActiveStackState.drainStack();
1293     fActiveStackState = SkPDFGraphicStackState();
1294 
1295     if (blendMode == SkBlendMode::kDstOver) {
1296         SkASSERT(!dst);
1297         if (fContentBuffer.bytesWritten() != 0) {
1298             if (fContent.bytesWritten() != 0) {
1299                 fContentBuffer.writeText("Q\nq\n");
1300                 fNeedsExtraSave = true;
1301             }
1302             fContentBuffer.prependToAndReset(&fContent);
1303             SkASSERT(fContentBuffer.bytesWritten() == 0);
1304         }
1305         return;
1306     }
1307     if (fContentBuffer.bytesWritten() != 0) {
1308         if (fContent.bytesWritten() != 0) {
1309             fContent.writeText("Q\nq\n");
1310             fNeedsExtraSave = true;
1311         }
1312         fContentBuffer.writeToAndReset(&fContent);
1313         SkASSERT(fContentBuffer.bytesWritten() == 0);
1314     }
1315 
1316     if (!dst) {
1317         SkASSERT(blendMode == SkBlendMode::kSrc ||
1318                  blendMode == SkBlendMode::kSrcOut);
1319         return;
1320     }
1321 
1322     SkASSERT(dst);
1323     // Changing the current content into a form-xobject will destroy the clip
1324     // objects which is fine since the xobject will already be clipped. However
1325     // if source has shape, we need to clip it too, so a copy of the clip is
1326     // saved.
1327 
1328     SkPaint stockPaint;
1329 
1330     SkPDFIndirectReference srcFormXObject;
1331     if (this->isContentEmpty()) {
1332         // If nothing was drawn and there's no shape, then the draw was a
1333         // no-op, but dst needs to be restored for that to be true.
1334         // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1335         // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1336         // reduces to Dst.
1337         if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1338                 blendMode == SkBlendMode::kSrcATop) {
1339             ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
1340             this->drawFormXObject(dst, content.stream());
1341             return;
1342         } else {
1343             blendMode = SkBlendMode::kClear;
1344         }
1345     } else {
1346         srcFormXObject = this->makeFormXObjectFromDevice();
1347     }
1348 
1349     // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1350     // without alpha.
1351     if (blendMode == SkBlendMode::kSrcATop) {
1352         // TODO(vandebo): In order to properly support SrcATop we have to track
1353         // the shape of what's been drawn at all times. It's the intersection of
1354         // the non-transparent parts of the device and the outlines (shape) of
1355         // all images and devices drawn.
1356         this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, true);
1357     } else {
1358         if (shape != nullptr) {
1359             // Draw shape into a form-xobject.
1360             SkPaint filledPaint;
1361             filledPaint.setColor(SK_ColorBLACK);
1362             filledPaint.setStyle(SkPaint::kFill_Style);
1363             SkClipStack empty;
1364             SkPDFDevice shapeDev(this->size(), fDocument, fInitialTransform);
1365             shapeDev.internalDrawPath(clipStack ? *clipStack : empty,
1366                                       SkMatrix::I(), *shape, filledPaint, true);
1367             this->drawFormXObjectWithMask(dst, shapeDev.makeFormXObjectFromDevice(),
1368                                           SkBlendMode::kSrcOver, true);
1369         } else {
1370             this->drawFormXObjectWithMask(dst, srcFormXObject, SkBlendMode::kSrcOver, true);
1371         }
1372     }
1373 
1374     if (blendMode == SkBlendMode::kClear) {
1375         return;
1376     } else if (blendMode == SkBlendMode::kSrc ||
1377             blendMode == SkBlendMode::kDstATop) {
1378         ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
1379         if (content) {
1380             this->drawFormXObject(srcFormXObject, content.stream());
1381         }
1382         if (blendMode == SkBlendMode::kSrc) {
1383             return;
1384         }
1385     } else if (blendMode == SkBlendMode::kSrcATop) {
1386         ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
1387         if (content) {
1388             this->drawFormXObject(dst, content.stream());
1389         }
1390     }
1391 
1392     SkASSERT(blendMode == SkBlendMode::kSrcIn   ||
1393              blendMode == SkBlendMode::kDstIn   ||
1394              blendMode == SkBlendMode::kSrcOut  ||
1395              blendMode == SkBlendMode::kDstOut  ||
1396              blendMode == SkBlendMode::kSrcATop ||
1397              blendMode == SkBlendMode::kDstATop ||
1398              blendMode == SkBlendMode::kModulate);
1399 
1400     if (blendMode == SkBlendMode::kSrcIn ||
1401             blendMode == SkBlendMode::kSrcOut ||
1402             blendMode == SkBlendMode::kSrcATop) {
1403         this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver,
1404                                       blendMode == SkBlendMode::kSrcOut);
1405         return;
1406     } else {
1407         SkBlendMode mode = SkBlendMode::kSrcOver;
1408         if (blendMode == SkBlendMode::kModulate) {
1409             this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, false);
1410             mode = SkBlendMode::kMultiply;
1411         }
1412         this->drawFormXObjectWithMask(dst, srcFormXObject, mode, blendMode == SkBlendMode::kDstOut);
1413         return;
1414     }
1415 }
1416 
isContentEmpty()1417 bool SkPDFDevice::isContentEmpty() {
1418     return fContent.bytesWritten() == 0 && fContentBuffer.bytesWritten() == 0;
1419 }
1420 
rect_to_size(const SkRect & r)1421 static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
1422 
color_filter(const SkImage * image,SkColorFilter * colorFilter)1423 static sk_sp<SkImage> color_filter(const SkImage* image,
1424                                    SkColorFilter* colorFilter) {
1425     auto surface =
1426         SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
1427     SkASSERT(surface);
1428     SkCanvas* canvas = surface->getCanvas();
1429     canvas->clear(SK_ColorTRANSPARENT);
1430     SkPaint paint;
1431     paint.setColorFilter(sk_ref_sp(colorFilter));
1432     canvas->drawImage(image, 0, 0, SkSamplingOptions(), &paint);
1433     return surface->makeImageSnapshot();
1434 }
1435 
1436 ////////////////////////////////////////////////////////////////////////////////
1437 
is_integer(SkScalar x)1438 static bool is_integer(SkScalar x) {
1439     return x == SkScalarTruncToScalar(x);
1440 }
1441 
is_integral(const SkRect & r)1442 static bool is_integral(const SkRect& r) {
1443     return is_integer(r.left()) &&
1444            is_integer(r.top()) &&
1445            is_integer(r.right()) &&
1446            is_integer(r.bottom());
1447 }
1448 
internalDrawImageRect(SkKeyedImage imageSubset,const SkRect * src,const SkRect & dst,const SkSamplingOptions & sampling,const SkPaint & srcPaint,const SkMatrix & ctm)1449 void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
1450                                         const SkRect* src,
1451                                         const SkRect& dst,
1452                                         const SkSamplingOptions& sampling,
1453                                         const SkPaint& srcPaint,
1454                                         const SkMatrix& ctm) {
1455     if (this->hasEmptyClip()) {
1456         return;
1457     }
1458     if (!imageSubset) {
1459         return;
1460     }
1461 
1462     // First, figure out the src->dst transform and subset the image if needed.
1463     SkIRect bounds = imageSubset.image()->bounds();
1464     SkRect srcRect = src ? *src : SkRect::Make(bounds);
1465     SkMatrix transform = SkMatrix::RectToRect(srcRect, dst);
1466     if (src && *src != SkRect::Make(bounds)) {
1467         if (!srcRect.intersect(SkRect::Make(bounds))) {
1468             return;
1469         }
1470         srcRect.roundOut(&bounds);
1471         transform.preTranslate(SkIntToScalar(bounds.x()),
1472                                SkIntToScalar(bounds.y()));
1473         if (bounds != imageSubset.image()->bounds()) {
1474             imageSubset = imageSubset.subset(bounds);
1475         }
1476         if (!imageSubset) {
1477             return;
1478         }
1479     }
1480 
1481     // If the image is opaque and the paint's alpha is too, replace
1482     // kSrc blendmode with kSrcOver.  http://crbug.com/473572
1483     SkTCopyOnFirstWrite<SkPaint> paint(srcPaint);
1484     if (!paint->isSrcOver() &&
1485         imageSubset.image()->isOpaque() &&
1486         kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false))
1487     {
1488         paint.writable()->setBlendMode(SkBlendMode::kSrcOver);
1489     }
1490 
1491     // Alpha-only images need to get their color from the shader, before
1492     // applying the colorfilter.
1493     if (imageSubset.image()->isAlphaOnly() && paint->getColorFilter()) {
1494         // must blend alpha image and shader before applying colorfilter.
1495         auto surface =
1496             SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
1497         SkCanvas* canvas = surface->getCanvas();
1498         SkPaint tmpPaint;
1499         // In the case of alpha images with shaders, the shader's coordinate
1500         // system is the image's coordiantes.
1501         tmpPaint.setShader(sk_ref_sp(paint->getShader()));
1502         tmpPaint.setColor4f(paint->getColor4f(), nullptr);
1503         canvas->clear(0x00000000);
1504         canvas->drawImage(imageSubset.image().get(), 0, 0, sampling, &tmpPaint);
1505         if (paint->getShader() != nullptr) {
1506             paint.writable()->setShader(nullptr);
1507         }
1508         imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1509         SkASSERT(!imageSubset.image()->isAlphaOnly());
1510     }
1511 
1512     if (imageSubset.image()->isAlphaOnly()) {
1513         // The ColorFilter applies to the paint color/shader, not the alpha layer.
1514         SkASSERT(nullptr == paint->getColorFilter());
1515 
1516         sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
1517         if (!mask) {
1518             return;
1519         }
1520         // PDF doesn't seem to allow masking vector graphics with an Image XObject.
1521         // Must mask with a Form XObject.
1522         sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
1523         {
1524             SkCanvas canvas(maskDevice);
1525             // This clip prevents the mask image shader from covering
1526             // entire device if unnecessary.
1527             canvas.clipRect(this->cs().bounds(this->bounds()));
1528             canvas.concat(ctm);
1529             if (paint->getMaskFilter()) {
1530                 SkPaint tmpPaint;
1531                 tmpPaint.setShader(mask->makeShader(SkSamplingOptions(), transform));
1532                 tmpPaint.setMaskFilter(sk_ref_sp(paint->getMaskFilter()));
1533                 canvas.drawRect(dst, tmpPaint);
1534             } else {
1535                 if (src && !is_integral(*src)) {
1536                     canvas.clipRect(dst);
1537                 }
1538                 canvas.concat(transform);
1539                 canvas.drawImage(mask, 0, 0);
1540             }
1541         }
1542         SkIRect maskDeviceBounds = maskDevice->cs().bounds(maskDevice->bounds()).roundOut();
1543         if (!ctm.isIdentity() && paint->getShader()) {
1544             transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
1545         }
1546         ScopedContentEntry content(this, &this->cs(), SkMatrix::I(), *paint);
1547         if (!content) {
1548             return;
1549         }
1550         this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
1551                 maskDevice->makeFormXObjectFromDevice(maskDeviceBounds, true), false,
1552                 SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), content.stream());
1553         SkPDFUtils::AppendRectangle(SkRect::Make(this->size()), content.stream());
1554         SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPathFillType::kWinding, content.stream());
1555         this->clearMaskOnGraphicState(content.stream());
1556         return;
1557     }
1558     if (paint->getMaskFilter()) {
1559         paint.writable()->setShader(imageSubset.image()->makeShader(SkSamplingOptions(),
1560                                                                     transform));
1561         SkPath path = SkPath::Rect(dst); // handles non-integral clipping.
1562         this->internalDrawPath(this->cs(), this->localToDevice(), path, *paint, true);
1563         return;
1564     }
1565     transform.postConcat(ctm);
1566 
1567     bool needToRestore = false;
1568     if (src && !is_integral(*src)) {
1569         // Need sub-pixel clipping to fix https://bug.skia.org/4374
1570         this->cs().save();
1571         this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
1572         needToRestore = true;
1573     }
1574     SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
1575 
1576     SkMatrix matrix = transform;
1577 
1578     // Rasterize the bitmap using perspective in a new bitmap.
1579     if (transform.hasPerspective()) {
1580         // Transform the bitmap in the new space, without taking into
1581         // account the initial transform.
1582         SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
1583         SkPath perspectiveOutline = SkPath::Rect(imageBounds).makeTransform(transform);
1584 
1585         // Retrieve the bounds of the new shape.
1586         SkRect outlineBounds = perspectiveOutline.getBounds();
1587         if (!outlineBounds.intersect(SkRect::Make(this->devClipBounds()))) {
1588             return;
1589         }
1590 
1591         // Transform the bitmap in the new space to the final space, to account for DPI
1592         SkRect physicalBounds = fInitialTransform.mapRect(outlineBounds);
1593         SkScalar scaleX = physicalBounds.width() / outlineBounds.width();
1594         SkScalar scaleY = physicalBounds.height() / outlineBounds.height();
1595 
1596         // TODO(edisonn): A better approach would be to use a bitmap shader
1597         // (in clamp mode) and draw a rect over the entire bounding box. Then
1598         // intersect perspectiveOutline to the clip. That will avoid introducing
1599         // alpha to the image while still giving good behavior at the edge of
1600         // the image.  Avoiding alpha will reduce the pdf size and generation
1601         // CPU time some.
1602 
1603         SkISize wh = rect_to_size(physicalBounds).toCeil();
1604 
1605         auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
1606         if (!surface) {
1607             return;
1608         }
1609         SkCanvas* canvas = surface->getCanvas();
1610         canvas->clear(SK_ColorTRANSPARENT);
1611 
1612         SkScalar deltaX = outlineBounds.left();
1613         SkScalar deltaY = outlineBounds.top();
1614 
1615         SkMatrix offsetMatrix = transform;
1616         offsetMatrix.postTranslate(-deltaX, -deltaY);
1617         offsetMatrix.postScale(scaleX, scaleY);
1618 
1619         // Translate the draw in the new canvas, so we perfectly fit the
1620         // shape in the bitmap.
1621         canvas->setMatrix(offsetMatrix);
1622         canvas->drawImage(imageSubset.image(), 0, 0);
1623         // Make sure the final bits are in the bitmap.
1624         surface->flushAndSubmit();
1625 
1626         // In the new space, we use the identity matrix translated
1627         // and scaled to reflect DPI.
1628         matrix.setScale(1 / scaleX, 1 / scaleY);
1629         matrix.postTranslate(deltaX, deltaY);
1630 
1631         imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1632         if (!imageSubset) {
1633             return;
1634         }
1635     }
1636 
1637     SkMatrix scaled;
1638     // Adjust for origin flip.
1639     scaled.setScale(SK_Scalar1, -SK_Scalar1);
1640     scaled.postTranslate(0, SK_Scalar1);
1641     // Scale the image up from 1x1 to WxH.
1642     SkIRect subset = imageSubset.image()->bounds();
1643     scaled.postScale(SkIntToScalar(subset.width()),
1644                      SkIntToScalar(subset.height()));
1645     scaled.postConcat(matrix);
1646     ScopedContentEntry content(this, &this->cs(), scaled, *paint);
1647     if (!content) {
1648         return;
1649     }
1650     if (content.needShape()) {
1651         SkPath shape = SkPath::Rect(SkRect::Make(subset)).makeTransform(matrix);
1652         content.setShape(shape);
1653     }
1654     if (!content.needSource()) {
1655         return;
1656     }
1657 
1658     if (SkColorFilter* colorFilter = paint->getColorFilter()) {
1659         sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
1660         imageSubset = SkKeyedImage(std::move(img));
1661         if (!imageSubset) {
1662             return;
1663         }
1664         // TODO(halcanary): de-dupe this by caching filtered images.
1665         // (maybe in the resource cache?)
1666     }
1667 
1668     SkBitmapKey key = imageSubset.key();
1669     SkPDFIndirectReference* pdfimagePtr = fDocument->fPDFBitmapMap.find(key);
1670     SkPDFIndirectReference pdfimage = pdfimagePtr ? *pdfimagePtr : SkPDFIndirectReference();
1671     if (!pdfimagePtr) {
1672         SkASSERT(imageSubset);
1673         pdfimage = SkPDFSerializeImage(imageSubset.image().get(), fDocument,
1674                                        fDocument->metadata().fEncodingQuality);
1675         SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
1676         fDocument->fPDFBitmapMap.set(key, pdfimage);
1677     }
1678     SkASSERT(pdfimage != SkPDFIndirectReference());
1679     this->drawFormXObject(pdfimage, content.stream());
1680 }
1681 
1682 ///////////////////////////////////////////////////////////////////////////////////////////////////
1683 
1684 
drawDevice(SkBaseDevice * device,const SkSamplingOptions & sampling,const SkPaint & paint)1685 void SkPDFDevice::drawDevice(SkBaseDevice* device, const SkSamplingOptions& sampling,
1686                              const SkPaint& paint) {
1687     SkASSERT(!paint.getImageFilter());
1688     SkASSERT(!paint.getMaskFilter());
1689 
1690     // Check if the source device is really a bitmapdevice (because that's what we returned
1691     // from createDevice (an image filter would go through drawSpecial, but createDevice uses
1692     // a raster device to apply color filters, too).
1693     SkPixmap pmap;
1694     if (device->peekPixels(&pmap)) {
1695         this->INHERITED::drawDevice(device, sampling, paint);
1696         return;
1697     }
1698 
1699     // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
1700     SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
1701 
1702     if (pdfDevice->isContentEmpty()) {
1703         return;
1704     }
1705 
1706     SkMatrix matrix = device->getRelativeTransform(*this);
1707     ScopedContentEntry content(this, &this->cs(), matrix, paint);
1708     if (!content) {
1709         return;
1710     }
1711     if (content.needShape()) {
1712         SkPath shape = SkPath::Rect(SkRect::Make(device->imageInfo().dimensions()));
1713         shape.transform(matrix);
1714         content.setShape(shape);
1715     }
1716     if (!content.needSource()) {
1717         return;
1718     }
1719     this->drawFormXObject(pdfDevice->makeFormXObjectFromDevice(), content.stream());
1720 }
1721 
drawSpecial(SkSpecialImage * srcImg,const SkMatrix & localToDevice,const SkSamplingOptions & sampling,const SkPaint & paint)1722 void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, const SkMatrix& localToDevice,
1723                               const SkSamplingOptions& sampling, const SkPaint& paint) {
1724     if (this->hasEmptyClip()) {
1725         return;
1726     }
1727     SkASSERT(!srcImg->isTextureBacked());
1728     SkASSERT(!paint.getMaskFilter() && !paint.getImageFilter());
1729 
1730     SkBitmap resultBM;
1731     if (srcImg->getROPixels(&resultBM)) {
1732         auto r = SkRect::MakeWH(resultBM.width(), resultBM.height());
1733         this->internalDrawImageRect(SkKeyedImage(resultBM), nullptr, r, sampling, paint,
1734                                     localToDevice);
1735     }
1736 }
1737 
makeSpecial(const SkBitmap & bitmap)1738 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
1739     return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap, this->surfaceProps());
1740 }
1741 
makeSpecial(const SkImage * image)1742 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
1743     return SkSpecialImage::MakeFromImage(nullptr, image->bounds(), image->makeNonTextureImage(),
1744                                          this->surfaceProps());
1745 }
1746 
getImageFilterCache()1747 SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
1748     // We always return a transient cache, so it is freed after each
1749     // filter traversal.
1750     return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
1751 }
1752