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