blob: 79365436c6909d4e7d6b1bc2329b8ab77194b263 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/pdf/SkPDFDevice.h"
halcanarye06ca962016-09-09 05:34:55 -07009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#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"
Mike Reedbd843302019-09-27 21:05:24 -040027#include "src/core/SkColorSpacePriv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050028#include "src/core/SkDraw.h"
29#include "src/core/SkGlyphRun.h"
30#include "src/core/SkImageFilterCache.h"
Michael Ludwig8ee6cf32019-08-02 09:57:04 -040031#include "src/core/SkImageFilter_Base.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050032#include "src/core/SkMaskFilterBase.h"
33#include "src/core/SkRasterClip.h"
Herb Derby81e84a62020-02-14 11:47:35 -050034#include "src/core/SkScalerCache.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050035#include "src/core/SkScopeExit.h"
Herb Derby2b35b7d2019-05-22 16:11:13 -040036#include "src/core/SkStrikeSpec.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050037#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"
Mike Reedc15afe42019-12-20 14:00:41 -050050#include "src/utils/SkClipStackUtils.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050051#include "src/utils/SkUTF.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040052
Hal Canary9e41c212018-09-03 12:00:23 -040053#include <vector>
54
Hal Canaryd12a6762017-05-26 17:01:16 -040055#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
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000065
Dominic Mazzoni8f233fc2020-03-06 11:20:45 -080066namespace {
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.
71class ScopedOutputMarkedContentTags {
72public:
73 ScopedOutputMarkedContentTags(int nodeId, SkPDFDocument* document, SkDynamicMemoryWStream* out)
74 : fOut(out)
75 , fMarkId(-1) {
76 if (nodeId) {
Dominic Mazzoni473c9f42020-07-07 14:55:35 -070077 fMarkId = document->createMarkIdForNodeId(nodeId);
Dominic Mazzoni8f233fc2020-03-06 11:20:45 -080078 }
79
80 if (fMarkId != -1) {
81 fOut->writeText("/P <</MCID ");
82 fOut->writeDecAsText(fMarkId);
83 fOut->writeText(" >>BDC\n");
84 }
85 }
86
87 ~ScopedOutputMarkedContentTags() {
88 if (fMarkId != -1) {
89 fOut->writeText("EMC\n");
90 }
91 }
92
93private:
94 SkDynamicMemoryWStream* fOut;
95 int fMarkId;
96};
97
John Stilesa6841be2020-08-06 14:11:56 -040098} // namespace
Dominic Mazzoni8f233fc2020-03-06 11:20:45 -080099
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000100// Utility functions
101
Hal Canary51329c92017-06-27 14:28:37 -0400102// This function destroys the mask and either frees or takes the pixels.
103sk_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
Hal Canaryd425a1d2017-07-12 13:13:51 -0400129sk_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));
Adlai Hollerbcfc5542020-08-27 12:44:07 -0400133 // TODO: support gpu images in pdf
134 if (!mask->readPixels(nullptr, SkImageInfo::MakeA8(w, h),
Hal Canaryd425a1d2017-07-12 13:13:51 -0400135 greyBitmap.getPixels(), greyBitmap.rowBytes(), 0, 0)) {
136 return nullptr;
137 }
Mike Reeddc607e32020-12-23 11:50:36 -0500138 greyBitmap.setImmutable();
139 return greyBitmap.asImage();
Hal Canaryd425a1d2017-07-12 13:13:51 -0400140}
141
Hal Canary9a3f5542018-12-10 19:59:07 -0500142static int add_resource(SkTHashSet<SkPDFIndirectReference>& resources, SkPDFIndirectReference ref) {
143 resources.add(ref);
144 return ref.fValue;
145}
146
Mike Reeda1361362017-03-07 09:37:29 -0500147static void draw_points(SkCanvas::PointMode mode,
148 size_t count,
149 const SkPoint* points,
150 const SkPaint& paint,
151 const SkIRect& bounds,
Mike Reeda1361362017-03-07 09:37:29 -0500152 SkBaseDevice* device) {
153 SkRasterClip rc(bounds);
154 SkDraw draw;
155 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
Brian Osman9aaec362020-05-08 14:54:37 -0400156 draw.fMatrixProvider = device;
Mike Reeda1361362017-03-07 09:37:29 -0500157 draw.fRC = &rc;
158 draw.drawPoints(mode, count, points, paint, device);
159}
160
Hal Canaryd12a6762017-05-26 17:01:16 -0400161// 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//
169static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
Hal Canarycfb0e022019-04-08 11:52:55 -0400170 SkASSERT(!ctm.isIdentity());
Hal Canaryd12a6762017-05-26 17:01:16 -0400171 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
Hal Canarycfb0e022019-04-08 11:52:55 -0400179static 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
Mike Reed90f4e9f2021-07-07 16:05:25 -0400183 if (!paint->isSrcOver() &&
Hal Canarycfb0e022019-04-08 11:52:55 -0400184 kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false))
185 {
186 paint.writable()->setBlendMode(SkBlendMode::kSrcOver);
187 }
Mike Klein96bce8f2019-10-23 11:26:46 -0500188 if (paint->getColorFilter()) {
189 // We assume here that PDFs all draw in sRGB.
190 SkPaintPriv::RemoveColorFilter(paint.writable(), sk_srgb_singleton());
Hal Canarycfb0e022019-04-08 11:52:55 -0400191 }
Mike Klein96bce8f2019-10-23 11:26:46 -0500192 SkASSERT(!paint->getColorFilter());
Hal Canarycfb0e022019-04-08 11:52:55 -0400193 return paint;
194}
195
196static void set_style(SkTCopyOnFirstWrite<SkPaint>* paint, SkPaint::Style style) {
197 if (paint->get()->getStyle() != style) {
198 paint->writable()->setStyle(style);
Hal Canaryd12a6762017-05-26 17:01:16 -0400199 }
200}
201
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000202/* 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 */
206static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
207 SkPath* outPath) {
208 SkASSERT(invPath.isInverseFillType());
Mike Reed58cc97a2020-08-24 15:15:01 -0400209 return Op(SkPath::Rect(bounds), invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000210}
211
Hal Canary8cb73762019-01-09 09:46:43 -0500212SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700213 // 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.
Hal Canary8cb73762019-01-09 09:46:43 -0500216
halcanary7a14b312015-10-01 07:28:13 -0700217 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800218 // to improve quality and file size (https://bug.skia.org/3043)
Hal Canary8cb73762019-01-09 09:46:43 -0500219 if (layerPaint && (layerPaint->getImageFilter() || layerPaint->getColorFilter())) {
reed7503d602016-07-15 14:23:29 -0700220 // need to return a raster device, which we will detect in drawDevice()
221 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700222 }
Hal Canary22b2d8c2017-07-19 14:46:12 -0400223 return new SkPDFDevice(cinfo.fInfo.dimensions(), fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000224}
225
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000226// 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.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000228class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000229public:
Mike Reeda1361362017-03-07 09:37:29 -0500230 ScopedContentEntry(SkPDFDevice* device,
Hal Canaryd892a9d2018-09-24 21:20:47 -0400231 const SkClipStack* clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000232 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500233 const SkPaint& paint,
Hal Canary8f37ce52018-12-28 11:40:10 -0500234 SkScalar textScale = 0)
Mike Reeda1361362017-03-07 09:37:29 -0500235 : fDevice(device)
Mike Reeda1361362017-03-07 09:37:29 -0500236 , fBlendMode(SkBlendMode::kSrcOver)
Hal Canaryb400d4d2018-09-26 16:33:52 -0400237 , fClipStack(clipStack)
Mike Reeda1361362017-03-07 09:37:29 -0500238 {
239 if (matrix.hasPerspective()) {
240 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
241 return;
242 }
Mike Reed90f4e9f2021-07-07 16:05:25 -0400243 fBlendMode = paint.getBlendMode_or(SkBlendMode::kSrcOver);
Hal Canary42137de2018-10-08 16:00:37 -0400244 fContentStream =
Hal Canary8f37ce52018-12-28 11:40:10 -0500245 fDevice->setUpContentEntry(clipStack, matrix, paint, textScale, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000246 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500247 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, SkScalar textScale = 0)
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400248 : ScopedContentEntry(dev, &dev->cs(), dev->localToDevice(), paint, textScale) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000249
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000250 ~ScopedContentEntry() {
Hal Canary42137de2018-10-08 16:00:37 -0400251 if (fContentStream) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000252 SkPath* shape = &fShape;
253 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700254 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000255 }
Hal Canary9a3f5542018-12-10 19:59:07 -0500256 fDevice->finishContentEntry(fClipStack, fBlendMode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000257 }
258 }
259
Hal Canary42137de2018-10-08 16:00:37 -0400260 explicit operator bool() const { return fContentStream != nullptr; }
261 SkDynamicMemoryWStream* stream() { return fContentStream; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000262
263 /* Returns true when we explicitly need the shape of the drawing. */
264 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700265 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:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000275 return true;
276 default:
277 return false;
278 }
279 }
280
281 /* Returns true unless we only need the shape of the drawing. */
282 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700283 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000284 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 */
293 void setShape(const SkPath& shape) {
294 fShape = shape;
295 }
296
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000297private:
Hal Canary42137de2018-10-08 16:00:37 -0400298 SkPDFDevice* fDevice = nullptr;
299 SkDynamicMemoryWStream* fContentStream = nullptr;
reed374772b2016-10-05 17:33:02 -0700300 SkBlendMode fBlendMode;
Hal Canary9a3f5542018-12-10 19:59:07 -0500301 SkPDFIndirectReference fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000302 SkPath fShape;
Hal Canaryb400d4d2018-09-26 16:33:52 -0400303 const SkClipStack* fClipStack;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000304};
305
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000306////////////////////////////////////////////////////////////////////////////////
307
Hal Canary7d06ab22018-09-10 14:39:13 -0400308SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc, const SkMatrix& transform)
reed589a39e2016-08-20 07:59:19 -0700309 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
310 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
Hal Canary7d06ab22018-09-10 14:39:13 -0400311 , fInitialTransform(transform)
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700312 , fNodeId(0)
Hal Canarya0622582017-06-29 18:51:35 -0400313 , fDocument(doc)
314{
Hal Canary22b2d8c2017-07-19 14:46:12 -0400315 SkASSERT(!pageSize.isEmpty());
Hal Canarya0622582017-06-29 18:51:35 -0400316}
robertphillips1f3923e2016-07-21 07:17:54 -0700317
Hal Canary9e41c212018-09-03 12:00:23 -0400318SkPDFDevice::~SkPDFDevice() = default;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000319
Hal Canary9e41c212018-09-03 12:00:23 -0400320void SkPDFDevice::reset() {
Hal Canary9a3f5542018-12-10 19:59:07 -0500321 fGraphicStateResources.reset();
322 fXObjectResources.reset();
323 fShaderResources.reset();
Hal Canaryb10f92e2018-11-16 17:01:50 -0500324 fFontResources.reset();
Hal Canary42137de2018-10-08 16:00:37 -0400325 fContent.reset();
Hal Canaryf5edf362019-04-10 11:00:01 -0400326 fActiveStackState = SkPDFGraphicStackState();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000327}
328
Mike Reeda1361362017-03-07 09:37:29 -0500329void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500330 if (!value) {
331 return;
332 }
Michael Ludwigfb3f3022020-02-20 13:23:58 -0500333 // Annotations are specified in absolute coordinates, so the page xform maps from device space
334 // to the global space, and applies the document transform.
Michael Ludwigb32708a2021-05-06 10:23:24 -0400335 SkMatrix pageXform = this->deviceToGlobal().asM33();
Michael Ludwigfb3f3022020-02-20 13:23:58 -0500336 pageXform.postConcat(fDocument->currentPageTransform());
Hal Canary9cd21682017-02-22 15:55:06 -0500337 if (rect.isEmpty()) {
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700338 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 }
Mike Reeda1361362017-03-07 09:37:29 -0500345 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
Michael Ludwigfb3f3022020-02-20 13:23:58 -0500346 SkPoint p = this->localToDevice().mapXY(rect.x(), rect.y());
Hal Canary77422782019-04-09 12:57:46 -0400347 pageXform.mapPoints(&p, 1);
348 auto pg = fDocument->currentPage();
349 fDocument->fNamedDestinations.push_back(SkPDFNamedDestination{sk_ref_sp(value), p, pg});
Mike Reeda1361362017-03-07 09:37:29 -0500350 }
351 return;
352 }
353 // Convert to path to handle non-90-degree rotations.
Mike Reed58cc97a2020-08-24 15:15:01 -0400354 SkPath path = SkPath::Rect(rect).makeTransform(this->localToDevice());
Mike Reeda1361362017-03-07 09:37:29 -0500355 SkPath clip;
Mike Reedc15afe42019-12-20 14:00:41 -0500356 SkClipStack_AsPath(this->cs(), &clip);
Mike Reeda1361362017-03-07 09:37:29 -0500357 Op(clip, path, kIntersect_SkPathOp, &path);
358 // PDF wants a rectangle only.
Michael Ludwigfb3f3022020-02-20 13:23:58 -0500359 SkRect transformedRect = pageXform.mapRect(path.getBounds());
Mike Reeda1361362017-03-07 09:37:29 -0500360 if (transformedRect.isEmpty()) {
361 return;
362 }
Dominic Mazzonic227f4a2020-03-24 08:27:54 -0700363
364 SkPDFLink::Type linkType = SkPDFLink::Type::kNone;
Mike Reeda1361362017-03-07 09:37:29 -0500365 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Dominic Mazzonic227f4a2020-03-24 08:27:54 -0700366 linkType = SkPDFLink::Type::kUrl;
Mike Reeda1361362017-03-07 09:37:29 -0500367 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Dominic Mazzonic227f4a2020-03-24 08:27:54 -0700368 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));
reedf70b5312016-03-04 16:36:20 -0800375 }
376}
377
Hal Canaryd12a6762017-05-26 17:01:16 -0400378void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
Hal Canaryabf8e412018-09-24 11:37:23 -0400379 SkMatrix inverse;
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400380 if (!this->localToDevice().invert(&inverse)) {
Hal Canaryabf8e412018-09-24 11:37:23 -0400381 return;
382 }
383 SkRect bbox = this->cs().bounds(this->bounds());
384 inverse.mapRect(&bbox);
385 bbox.roundOut(&bbox);
Hal Canaryb4e528d2018-03-09 16:02:15 -0500386 if (this->hasEmptyClip()) {
387 return;
388 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400389 SkPaint newPaint = srcPaint;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000390 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryabf8e412018-09-24 11:37:23 -0400391 this->drawRect(bbox, newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000392}
393
Mike Reeda1361362017-03-07 09:37:29 -0500394void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700395 size_t count,
396 const SkPoint* points,
397 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500398 if (this->hasEmptyClip()) {
399 return;
400 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000401 if (count == 0) {
402 return;
403 }
Hal Canarycfb0e022019-04-08 11:52:55 -0400404 SkTCopyOnFirstWrite<SkPaint> paint(clean_paint(srcPaint));
405
406
407
408 if (SkCanvas::kPoints_PointMode != mode) {
409 set_style(&paint, SkPaint::kStroke_Style);
410 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000411
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000412 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
413 // We only use this when there's a path effect because of the overhead
414 // of multiple calls to setUpContentEntry it causes.
Hal Canarycfb0e022019-04-08 11:52:55 -0400415 if (paint->getPathEffect()) {
Brian Osman9aaec362020-05-08 14:54:37 -0400416 draw_points(mode, count, points, *paint, this->devClipBounds(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000417 return;
418 }
419
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000420
Hal Canarycfb0e022019-04-08 11:52:55 -0400421 if (mode == SkCanvas::kPoints_PointMode && paint->getStrokeCap() != SkPaint::kRound_Cap) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000422 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.
Hal Canarycfb0e022019-04-08 11:52:55 -0400425 set_style(&paint, SkPaint::kFill_Style);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000426 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);
Hal Canarycfb0e022019-04-08 11:52:55 -0400431 this->drawRect(r, *paint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000432 }
433 return;
434 } else {
Hal Canarycfb0e022019-04-08 11:52:55 -0400435 if (paint->getStrokeCap() != SkPaint::kRound_Cap) {
436 paint.writable()->setStrokeCap(SkPaint::kRound_Cap);
437 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000438 }
439 }
440
Mike Reeda1361362017-03-07 09:37:29 -0500441 ScopedContentEntry content(this, *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400442 if (!content) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000443 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000444 }
Hal Canary51329c92017-06-27 14:28:37 -0400445 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000446 switch (mode) {
447 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400448 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000449 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400450 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000451 }
Hal Canary51329c92017-06-27 14:28:37 -0400452 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000453 break;
454 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000455 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400456 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);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000459 }
460 break;
461 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000462 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
463 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400464 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
465 SkPDFUtils::ClosePath(contentStream);
466 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000467 }
468 break;
469 default:
470 SkASSERT(false);
471 }
472}
473
Hal Canaryb4719cc2019-04-10 09:04:34 -0400474void SkPDFDevice::drawRect(const SkRect& rect, const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000475 SkRect r = rect;
476 r.sort();
Mike Reed58cc97a2020-08-24 15:15:01 -0400477 this->internalDrawPath(this->cs(), this->localToDevice(), SkPath::Rect(r), paint, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000478}
479
Hal Canaryb4719cc2019-04-10 09:04:34 -0400480void SkPDFDevice::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
Mike Reed58cc97a2020-08-24 15:15:01 -0400481 this->internalDrawPath(this->cs(), this->localToDevice(), SkPath::RRect(rrect), paint, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000482}
483
Hal Canaryb4719cc2019-04-10 09:04:34 -0400484void SkPDFDevice::drawOval(const SkRect& oval, const SkPaint& paint) {
Mike Reed58cc97a2020-08-24 15:15:01 -0400485 this->internalDrawPath(this->cs(), this->localToDevice(), SkPath::Oval(oval), paint, true);
reed89443ab2014-06-27 11:34:19 -0700486}
487
Hal Canaryb4719cc2019-04-10 09:04:34 -0400488void SkPDFDevice::drawPath(const SkPath& path, const SkPaint& paint, bool pathIsMutable) {
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400489 this->internalDrawPath(this->cs(), this->localToDevice(), path, paint, pathIsMutable);
Mike Reeda1361362017-03-07 09:37:29 -0500490}
491
Hal Canaryd12a6762017-05-26 17:01:16 -0400492void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
493 const SkMatrix& ctm,
494 const SkPath& origPath,
Robert Phillips137ca522018-08-15 10:14:33 -0400495 const SkPaint& origPaint) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400496 SkASSERT(origPaint.getMaskFilter());
497 SkPath path(origPath);
498 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
Robert Phillips137ca522018-08-15 10:14:33 -0400499
Hal Canaryd12a6762017-05-26 17:01:16 -0400500 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
501 ? SkStrokeRec::kFill_InitStyle
502 : SkStrokeRec::kHairline_InitStyle;
503 path.transform(ctm, &path);
504
Hal Canary22b2d8c2017-07-19 14:46:12 -0400505 SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
Hal Canaryd12a6762017-05-26 17:01:16 -0400506 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;
Mike Reed80747ef2018-01-23 15:29:32 -0500515 if (!as_MFB(paint->getMaskFilter())->filterMask(&dstMask, sourceMask, ctm, &margin)) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400516 return;
517 }
Hal Canary51329c92017-06-27 14:28:37 -0400518 SkIRect dstMaskBounds = dstMask.fBounds;
519 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400520 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
521 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400522 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400523 {
Herb Derbyefe39bc2018-05-01 17:06:20 -0400524 SkCanvas canvas(maskDevice);
Hal Canary51329c92017-06-27 14:28:37 -0400525 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400526 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400527 if (!ctm.isIdentity() && paint->getShader()) {
528 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
529 }
Hal Canaryd892a9d2018-09-24 21:20:47 -0400530 ScopedContentEntry content(this, &clipStack, SkMatrix::I(), *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400531 if (!content) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400532 return;
533 }
Hal Canary6028fa72019-04-10 15:33:06 -0400534 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
535 maskDevice->makeFormXObjectFromDevice(dstMaskBounds, true), false,
536 SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), content.stream());
Hal Canary51329c92017-06-27 14:28:37 -0400537 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
Mike Reedcf0e3c62019-12-03 16:26:15 -0500538 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
Hal Canary51329c92017-06-27 14:28:37 -0400539 this->clearMaskOnGraphicState(content.stream());
540}
Hal Canaryd12a6762017-05-26 17:01:16 -0400541
Hal Canary9a3f5542018-12-10 19:59:07 -0500542void SkPDFDevice::setGraphicState(SkPDFIndirectReference gs, SkDynamicMemoryWStream* content) {
543 SkPDFUtils::ApplyGraphicState(add_resource(fGraphicStateResources, gs), content);
Hal Canary3b8b11e2018-09-29 22:31:34 -0400544}
545
Hal Canary51329c92017-06-27 14:28:37 -0400546void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400547 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canary4ca9fa32018-12-21 16:15:01 -0500548 SkPDFIndirectReference& noSMaskGS = fDocument->fNoSmaskGraphicState;
Hal Canaryc02de0b2017-06-28 13:14:03 -0400549 if (!noSMaskGS) {
Hal Canary9a3f5542018-12-10 19:59:07 -0500550 SkPDFDict tmp("ExtGState");
551 tmp.insertName("SMask", "None");
552 noSMaskGS = fDocument->emit(tmp);
Hal Canaryc02de0b2017-06-28 13:14:03 -0400553 }
Hal Canary3b8b11e2018-09-29 22:31:34 -0400554 this->setGraphicState(noSMaskGS, contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400555}
556
Mike Reeda1361362017-03-07 09:37:29 -0500557void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
558 const SkMatrix& ctm,
559 const SkPath& origPath,
560 const SkPaint& srcPaint,
Mike Reeda1361362017-03-07 09:37:29 -0500561 bool pathIsMutable) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500562 if (clipStack.isEmpty(this->bounds())) {
563 return;
564 }
Hal Canarycfb0e022019-04-08 11:52:55 -0400565 SkTCopyOnFirstWrite<SkPaint> paint(clean_paint(srcPaint));
halcanary682ee012016-01-28 10:59:34 -0800566 SkPath modifiedPath;
567 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000568
Hal Canarycfb0e022019-04-08 11:52:55 -0400569 if (paint->getMaskFilter()) {
570 this->internalDrawPathWithFilter(clipStack, ctm, origPath, *paint);
Hal Canaryd12a6762017-05-26 17:01:16 -0400571 return;
572 }
573
Mike Reeda1361362017-03-07 09:37:29 -0500574 SkMatrix matrix = ctm;
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000575
Hal Canarycfb0e022019-04-08 11:52:55 -0400576 if (paint->getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400577 if (clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000578 return;
579 }
halcanary682ee012016-01-28 10:59:34 -0800580 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400581 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000582 pathPtr = &modifiedPath;
583 pathIsMutable = true;
584 }
Hal Canarycfb0e022019-04-08 11:52:55 -0400585 if (paint->getFillPath(*pathPtr, pathPtr)) {
586 set_style(&paint, SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000587 } else {
Hal Canarycfb0e022019-04-08 11:52:55 -0400588 set_style(&paint, SkPaint::kStroke_Style);
589 if (paint->getStrokeWidth() != 0) {
590 paint.writable()->setStrokeWidth(0);
591 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000592 }
Hal Canarycfb0e022019-04-08 11:52:55 -0400593 paint.writable()->setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000594 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000595
Hal Canarycfb0e022019-04-08 11:52:55 -0400596 if (this->handleInversePath(*pathPtr, *paint, pathIsMutable)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000597 return;
598 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400599 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
600 if (!pathIsMutable) {
601 modifiedPath = origPath;
602 pathPtr = &modifiedPath;
603 pathIsMutable = true;
604 }
605 pathPtr->transform(matrix);
Hal Canarycfb0e022019-04-08 11:52:55 -0400606 if (paint->getShader()) {
607 transform_shader(paint.writable(), matrix);
Hal Canaryd12a6762017-05-26 17:01:16 -0400608 }
609 matrix = SkMatrix::I();
610 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000611
Hal Canarycfb0e022019-04-08 11:52:55 -0400612 ScopedContentEntry content(this, &clipStack, matrix, *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400613 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000614 return;
615 }
Hal Canarydfaa0572017-11-27 09:33:44 -0500616 constexpr SkScalar kToleranceScale = 0.0625f; // smaller = better conics (circles).
Hal Canary385468f2017-02-13 11:03:23 -0500617 SkScalar matrixScale = matrix.mapRadius(1.0f);
Hal Canarydfaa0572017-11-27 09:33:44 -0500618 SkScalar tolerance = matrixScale > 0.0f ? kToleranceScale / matrixScale : kToleranceScale;
halcanary8b2bc252015-10-06 09:41:47 -0700619 bool consumeDegeratePathSegments =
Hal Canarycfb0e022019-04-08 11:52:55 -0400620 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(),
Hal Canary385468f2017-02-13 11:03:23 -0500624 tolerance);
Mike Reedcf0e3c62019-12-03 16:26:15 -0500625 SkPDFUtils::PaintPath(paint->getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000626}
627
Hal Canary7cbf5e32017-07-12 13:10:23 -0400628////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400629
Mike Reeda1361362017-03-07 09:37:29 -0500630void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400631 const SkRect* src,
632 const SkRect& dst,
Mike Reedd8ff3132021-01-02 12:57:04 -0500633 const SkSamplingOptions& sampling,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400634 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400635 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400636 SkASSERT(image);
637 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
Mike Reedd8ff3132021-01-02 12:57:04 -0500638 src, dst, sampling, paint, this->localToDevice());
Hal Canaryf50ff392016-09-30 10:25:39 -0400639}
640
Hal Canary7cbf5e32017-07-12 13:10:23 -0400641void 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());
Mike Reedd8ff3132021-01-02 12:57:04 -0500644 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, SkSamplingOptions(), paint,
645 SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -0700646}
647
Hal Canary7cbf5e32017-07-12 13:10:23 -0400648////////////////////////////////////////////////////////////////////////////////
649
halcanaryf0c30f52016-07-15 13:35:45 -0700650namespace {
651class GlyphPositioner {
652public:
653 GlyphPositioner(SkDynamicMemoryWStream* content,
654 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700655 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700656 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700657 , fCurrentMatrixOrigin(origin)
Hal Canary8ef78ea2018-10-01 13:38:30 -0400658 , fTextSkewX(textSkewX) {
halcanaryf0c30f52016-07-15 13:35:45 -0700659 }
halcanary4871f222016-08-26 13:17:44 -0700660 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700661 void flush() {
662 if (fInText) {
663 fContent->writeText("> Tj\n");
664 fInText = false;
665 }
666 }
Ben Wagnera4625e22021-08-13 15:45:22 -0400667 void setFont(SkPDFFont* pdfFont) {
Hal Canary8ef78ea2018-10-01 13:38:30 -0400668 this->flush();
Ben Wagnera4625e22021-08-13 15:45:22 -0400669 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;
Hal Canary8ef78ea2018-10-01 13:38:30 -0400674 }
Ben Wagnera4625e22021-08-13 15:45:22 -0400675 void writeGlyph(uint16_t glyph, SkScalar advanceWidth, SkPoint xy) {
676 SkASSERT(fPDFFont);
halcanaryc2f9ec12016-09-12 08:55:29 -0700677 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 }
Hal Canary98caedd2018-07-23 10:50:49 -0400690 SkPoint position = xy - fCurrentMatrixOrigin;
Ben Wagnera4625e22021-08-13 15:45:22 -0400691 if (!fViewersAgreeOnXAdvance || position != SkPoint{fXAdvance, 0}) {
Hal Canary98caedd2018-07-23 10:50:49 -0400692 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;
Ben Wagnera4625e22021-08-13 15:45:22 -0400699 fViewersAgreeOnXAdvance = true;
halcanaryf0c30f52016-07-15 13:35:45 -0700700 }
Hal Canary98caedd2018-07-23 10:50:49 -0400701 fXAdvance += advanceWidth;
Ben Wagnera4625e22021-08-13 15:45:22 -0400702 if (!fViewersAgreeOnAdvancesInFont) {
703 fViewersAgreeOnXAdvance = false;
704 }
halcanaryf0c30f52016-07-15 13:35:45 -0700705 if (!fInText) {
706 fContent->writeText("<");
707 fInText = true;
708 }
Ben Wagnera4625e22021-08-13 15:45:22 -0400709 if (fPDFFont->multiByteGlyphs()) {
halcanaryf0c30f52016-07-15 13:35:45 -0700710 SkPDFUtils::WriteUInt16BE(fContent, glyph);
711 } else {
712 SkASSERT(0 == glyph >> 8);
713 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
714 }
halcanaryf0c30f52016-07-15 13:35:45 -0700715 }
716
717private:
718 SkDynamicMemoryWStream* fContent;
Ben Wagnera4625e22021-08-13 15:45:22 -0400719 SkPDFFont* fPDFFont = nullptr;
halcanary4871f222016-08-26 13:17:44 -0700720 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -0700721 SkScalar fXAdvance = 0.0f;
Ben Wagnera4625e22021-08-13 15:45:22 -0400722 bool fViewersAgreeOnAdvancesInFont = true;
723 bool fViewersAgreeOnXAdvance = true;
halcanaryc2f9ec12016-09-12 08:55:29 -0700724 SkScalar fTextSkewX;
halcanaryc2f9ec12016-09-12 08:55:29 -0700725 bool fInText = false;
726 bool fInitialized = false;
halcanaryf0c30f52016-07-15 13:35:45 -0700727};
728} // namespace
729
Hal Canary46cc3da2018-05-09 11:50:34 -0400730static SkUnichar map_glyph(const std::vector<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
731 return glyph < glyphToUnicode.size() ? glyphToUnicode[SkToInt(glyph)] : -1;
halcanaryf59d18a2016-09-16 14:44:57 -0700732}
733
Hal Canary575be302018-09-28 15:01:14 -0400734namespace {
735struct PositionedGlyph {
736 SkPoint fPos;
737 SkGlyphID fGlyph;
738};
John Stilesa6841be2020-08-06 14:11:56 -0400739} // namespace
Hal Canaryd12a6762017-05-26 17:01:16 -0400740
Herb Derby02e91502019-07-03 10:57:33 -0400741static SkRect get_glyph_bounds_device_space(const SkGlyph* glyph,
Hal Canary699b8732017-06-13 12:13:29 -0400742 SkScalar xScale, SkScalar yScale,
743 SkPoint xy, const SkMatrix& ctm) {
Mike Reed1f607332020-05-21 12:11:27 -0400744 SkRect glyphBounds = SkMatrix::Scale(xScale, yScale).mapRect(glyph->rect());
Hal Canary699b8732017-06-13 12:13:29 -0400745 glyphBounds.offset(xy);
746 ctm.mapRect(&glyphBounds); // now in dev space.
747 return glyphBounds;
748}
749
750static 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
Herb Derby95e17602018-12-06 17:11:43 -0500755void SkPDFDevice::drawGlyphRunAsPath(
756 const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
Hal Canary8f37ce52018-12-28 11:40:10 -0500757 const SkFont& font = glyphRun.font();
Hal Canary575be302018-09-28 15:01:14 -0400758 SkPath path;
Herb Derby4fce0832018-10-02 11:04:29 -0400759
Mike Reedab8f2972018-12-05 13:20:29 -0500760 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);
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400777 this->internalDrawPath(this->cs(), this->localToDevice(), path, runPaint, true);
Hal Canary575be302018-09-28 15:01:14 -0400778
Herb Derby95e17602018-12-06 17:11:43 -0500779 SkFont transparentFont = glyphRun.font();
780 transparentFont.setEmbolden(false); // Stop Recursion
781 SkGlyphRun tmpGlyphRun(glyphRun, transparentFont);
782
Herb Derby9bb6b7e2018-11-02 13:57:58 -0400783 SkPaint transparent;
Herb Derby9bb6b7e2018-11-02 13:57:58 -0400784 transparent.setColor(SK_ColorTRANSPARENT);
Herb Derby9bb6b7e2018-11-02 13:57:58 -0400785
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400786 if (this->localToDevice().hasPerspective()) {
787 SkAutoDeviceTransformRestore adr(this, SkMatrix::I());
Herb Derby95e17602018-12-06 17:11:43 -0500788 this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
Hal Canary575be302018-09-28 15:01:14 -0400789 } else {
Herb Derby95e17602018-12-06 17:11:43 -0500790 this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
Hal Canary575be302018-09-28 15:01:14 -0400791 }
Hal Canary575be302018-09-28 15:01:14 -0400792}
793
Herb Derby02e91502019-07-03 10:57:33 -0400794static bool needs_new_font(SkPDFFont* font, const SkGlyph* glyph,
Hal Canary688afdd2018-10-17 14:57:53 -0400795 SkAdvancedTypefaceMetrics::FontType fontType) {
Herb Derby02e91502019-07-03 10:57:33 -0400796 if (!font || !font->hasGlyph(glyph->getGlyphID())) {
Hal Canary688afdd2018-10-17 14:57:53 -0400797 return true;
798 }
799 if (fontType == SkAdvancedTypefaceMetrics::kOther_Font) {
800 return false;
801 }
Herb Derbyf0e75812019-06-12 11:14:50 -0400802 if (glyph->isEmpty()) {
Hal Canary688afdd2018-10-17 14:57:53 -0400803 return false;
804 }
805
Herb Derby02e91502019-07-03 10:57:33 -0400806 bool bitmapOnly = nullptr == glyph->path();
Hal Canary688afdd2018-10-17 14:57:53 -0400807 bool convertedToType3 = (font->getType() == SkAdvancedTypefaceMetrics::kOther_Font);
808 return convertedToType3 != bitmapOnly;
809}
810
Herb Derby95e17602018-12-06 17:11:43 -0500811void SkPDFDevice::internalDrawGlyphRun(
812 const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
Hal Canary98caedd2018-07-23 10:50:49 -0400813
Herb Derby02e91502019-07-03 10:57:33 -0400814 const SkGlyphID* glyphIDs = glyphRun.glyphsIDs().data();
Herb Derbyaedc9d22018-10-25 12:27:07 -0400815 uint32_t glyphCount = SkToU32(glyphRun.glyphsIDs().size());
Hal Canary8f37ce52018-12-28 11:40:10 -0500816 const SkFont& glyphRunFont = glyphRun.font();
Herb Derby4fce0832018-10-02 11:04:29 -0400817
Herb Derby02e91502019-07-03 10:57:33 -0400818 if (!glyphCount || !glyphIDs || glyphRunFont.getSize() <= 0 || this->hasEmptyClip()) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400819 return;
820 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500821 if (runPaint.getPathEffect()
822 || runPaint.getMaskFilter()
823 || glyphRunFont.isEmbolden()
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400824 || this->localToDevice().hasPerspective()
Hal Canary8f37ce52018-12-28 11:40:10 -0500825 || SkPaint::kFill_Style != runPaint.getStyle()) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400826 // Stroked Text doesn't work well with Type3 fonts.
Herb Derby95e17602018-12-06 17:11:43 -0500827 this->drawGlyphRunAsPath(glyphRun, offset, runPaint);
Hal Canarye9a29c42018-12-07 13:44:26 -0500828 return;
halcanarye06ca962016-09-09 05:34:55 -0700829 }
Herb Derby087fad72019-01-22 14:45:16 -0500830 SkTypeface* typeface = glyphRunFont.getTypefaceOrDefault();
halcanary4ed2f012016-08-15 18:40:07 -0700831 if (!typeface) {
832 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
833 return;
834 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500835
Hal Canary4ca9fa32018-12-21 16:15:01 -0500836 const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, fDocument);
halcanary4871f222016-08-26 13:17:44 -0700837 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -0700838 return;
839 }
Hal Canary688afdd2018-10-17 14:57:53 -0400840 SkAdvancedTypefaceMetrics::FontType fontType = SkPDFFont::FontType(*metrics);
841
Hal Canary4ca9fa32018-12-21 16:15:01 -0500842 const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(typeface, fDocument);
Hal Canary46cc3da2018-05-09 11:50:34 -0400843
Hal Canary98caedd2018-07-23 10:50:49 -0400844 SkClusterator clusterator(glyphRun);
Hal Canaryaa3af7b2017-03-06 16:18:49 -0500845
846 int emSize;
Herb Derby36a54c12019-06-06 10:50:56 -0400847 SkStrikeSpec strikeSpec = SkStrikeSpec::MakePDFVector(*typeface, &emSize);
Hal Canaryaa3af7b2017-03-06 16:18:49 -0500848
Hal Canary8f37ce52018-12-28 11:40:10 -0500849 SkScalar textSize = glyphRunFont.getSize();
850 SkScalar advanceScale = textSize * glyphRunFont.getScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -0700851
Hal Canary699b8732017-06-13 12:13:29 -0400852 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
853 SkScalar textScaleY = textSize / emSize;
Hal Canary8f37ce52018-12-28 11:40:10 -0500854 SkScalar textScaleX = advanceScale + glyphRunFont.getSkewX() * textScaleY;
Hal Canary699b8732017-06-13 12:13:29 -0400855
Hal Canary22b2d8c2017-07-19 14:46:12 -0400856 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -0400857
Hal Canarycfb0e022019-04-08 11:52:55 -0400858 SkTCopyOnFirstWrite<SkPaint> paint(clean_paint(runPaint));
859 ScopedContentEntry content(this, *paint, glyphRunFont.getScaleX());
Hal Canary8f37ce52018-12-28 11:40:10 -0500860 if (!content) {
861 return;
862 }
863 SkDynamicMemoryWStream* out = content.stream();
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700864
Hal Canary8f37ce52018-12-28 11:40:10 -0500865 out->writeText("BT\n");
Hal Canary8f37ce52018-12-28 11:40:10 -0500866 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
Hal Canary9b9510a2017-07-18 09:39:00 -0400867
Dominic Mazzoni8f233fc2020-03-06 11:20:45 -0800868 ScopedOutputMarkedContentTags mark(fNodeId, fDocument, out);
869
Ben Wagnerc19459b2020-04-30 21:13:51 -0400870 const int numGlyphs = typeface->countGlyphs();
Hal Canary9b9510a2017-07-18 09:39:00 -0400871
Hal Canary8f37ce52018-12-28 11:40:10 -0500872 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;
Hal Canary9b9510a2017-07-18 09:39:00 -0400878
Herb Derby02e91502019-07-03 10:57:33 -0400879 SkBulkGlyphMetricsAndPaths paths{strikeSpec};
880 auto glyphs = paths.glyphs(glyphRun.glyphsIDs());
Herb Derbyea41c7b2019-05-22 16:40:58 -0400881
Hal Canary8f37ce52018-12-28 11:40:10 -0500882 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;
halcanaryf59d18a2016-09-16 14:44:57 -0700898 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500899 if (textPtr < textEnd || // more characters left
900 glyphLimit > index + 1 || // toUnicode wouldn't work
Herb Derby02e91502019-07-03 10:57:33 -0400901 unichar != map_glyph(glyphToUnicode, glyphIDs[index])) // test single Unichar map
Hal Canary8f37ce52018-12-28 11:40:10 -0500902 {
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) {
Herb Derby02e91502019-07-03 10:57:33 -0400921 SkGlyphID gid = glyphIDs[index];
Ben Wagnerc19459b2020-04-30 21:13:51 -0400922 if (numGlyphs <= gid) {
Hal Canary8f37ce52018-12-28 11:40:10 -0500923 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(
Herb Derby02e91502019-07-03 10:57:33 -0400928 glyphs[index], textScaleX, textScaleY,
Michael Ludwigc89d1b52019-10-18 11:32:56 -0400929 xy + offset, this->localToDevice());
Hal Canary8f37ce52018-12-28 11:40:10 -0500930 if (glyphBounds.isEmpty()) {
931 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
Hal Canary9b9510a2017-07-18 09:39:00 -0400932 continue;
halcanaryf59d18a2016-09-16 14:44:57 -0700933 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500934 } else {
935 if (!clipStackBounds.intersects(glyphBounds)) {
936 continue; // reject glyphs as out of bounds
Hal Canary688afdd2018-10-17 14:57:53 -0400937 }
halcanaryf59d18a2016-09-16 14:44:57 -0700938 }
Herb Derby02e91502019-07-03 10:57:33 -0400939 if (needs_new_font(font, glyphs[index], fontType)) {
Hal Canary8f37ce52018-12-28 11:40:10 -0500940 // Not yet specified font or need to switch font.
Herb Derby02e91502019-07-03 10:57:33 -0400941 font = SkPDFFont::GetFontResource(fDocument, glyphs[index], typeface);
Hal Canary8f37ce52018-12-28 11:40:10 -0500942 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
Ben Wagnera4625e22021-08-13 15:45:22 -0400943 glyphPositioner.setFont(font);
Hal Canary8f37ce52018-12-28 11:40:10 -0500944 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);
Ben Wagnera4625e22021-08-13 15:45:22 -0400952 SkGlyphID encodedGlyph = font->glyphToPDFFontEncoding(gid);
Herb Derby02e91502019-07-03 10:57:33 -0400953 SkScalar advance = advanceScale * glyphs[index]->advanceX();
Ben Wagnera4625e22021-08-13 15:45:22 -0400954 glyphPositioner.writeGlyph(encodedGlyph, advance, xy);
Hal Canary9b9510a2017-07-18 09:39:00 -0400955 }
956 }
halcanary4ed2f012016-08-15 18:40:07 -0700957}
958
Herb Derby97abbee2021-04-09 15:06:21 -0400959void SkPDFDevice::onDrawGlyphRunList(const SkGlyphRunList& glyphRunList, const SkPaint& paint) {
960 SkASSERT(!glyphRunList.hasRSXForm());
Herb Derbyb935cf82018-07-26 16:54:18 -0400961 for (const SkGlyphRun& glyphRun : glyphRunList) {
Herb Derby0da2c142021-03-22 15:28:23 -0400962 this->internalDrawGlyphRun(glyphRun, glyphRunList.origin(), paint);
halcanarye06ca962016-09-09 05:34:55 -0700963 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000964}
965
Mike Reed5caf9352020-03-02 14:57:09 -0500966void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500967 if (this->hasEmptyClip()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000968 return;
969 }
reed@google.com85e143c2013-12-30 15:51:25 +0000970 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000971}
972
Hal Canary9a3f5542018-12-10 19:59:07 -0500973void SkPDFDevice::drawFormXObject(SkPDFIndirectReference xObject, SkDynamicMemoryWStream* content) {
Dominic Mazzoni8f233fc2020-03-06 11:20:45 -0800974 ScopedOutputMarkedContentTags mark(fNodeId, fDocument, content);
975
Hal Canary9a3f5542018-12-10 19:59:07 -0500976 SkASSERT(xObject);
Hal Canary3b8b11e2018-09-29 22:31:34 -0400977 SkPDFWriteResourceName(content, SkPDFResourceType::kXObject,
Hal Canary9a3f5542018-12-10 19:59:07 -0500978 add_resource(fXObjectResources, xObject));
Hal Canarye650b852018-09-12 09:12:36 -0400979 content->writeText(" Do\n");
980}
981
reede8f30622016-03-23 18:59:25 -0700982sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
983 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -0700984}
985
Hal Canary9a3f5542018-12-10 19:59:07 -0500986static std::vector<SkPDFIndirectReference> sort(const SkTHashSet<SkPDFIndirectReference>& src) {
987 std::vector<SkPDFIndirectReference> dst;
988 dst.reserve(src.count());
John Stiles65b48272020-12-22 17:18:34 -0500989 for (SkPDFIndirectReference ref : src) {
990 dst.push_back(ref);
991 }
Hal Canary9a3f5542018-12-10 19:59:07 -0500992 std::sort(dst.begin(), dst.end(),
993 [](SkPDFIndirectReference a, SkPDFIndirectReference b) { return a.fValue < b.fValue; });
994 return dst;
995}
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000996
Hal Canary74801582018-12-18 16:30:41 -0500997std::unique_ptr<SkPDFDict> SkPDFDevice::makeResourceDict() {
Hal Canary9a3f5542018-12-10 19:59:07 -0500998 return SkPDFMakeResourceDict(sort(fGraphicStateResources),
999 sort(fShaderResources),
1000 sort(fXObjectResources),
1001 sort(fFontResources));
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001002}
1003
Hal Canaryb400d4d2018-09-26 16:33:52 -04001004std::unique_ptr<SkStreamAsset> SkPDFDevice::content() {
1005 if (fActiveStackState.fContentStream) {
1006 fActiveStackState.drainStack();
Hal Canaryf5edf362019-04-10 11:00:01 -04001007 fActiveStackState = SkPDFGraphicStackState();
Hal Canaryb400d4d2018-09-26 16:33:52 -04001008 }
Hal Canary42137de2018-10-08 16:00:37 -04001009 if (fContent.bytesWritten() == 0) {
Mike Kleinf46d5ca2019-12-11 10:45:01 -05001010 return std::make_unique<SkMemoryStream>();
Hal Canary42137de2018-10-08 16:00:37 -04001011 }
halcanary334fcbc2015-02-24 12:56:16 -08001012 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001013 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
Hal Canaryf5edf362019-04-10 11:00:01 -04001014 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001015 }
Hal Canary42137de2018-10-08 16:00:37 -04001016 if (fNeedsExtraSave) {
1017 buffer.writeText("q\n");
halcanary2be7e012016-03-28 11:58:08 -07001018 }
Hal Canary42137de2018-10-08 16:00:37 -04001019 fContent.writeToAndReset(&buffer);
1020 if (fNeedsExtraSave) {
1021 buffer.writeText("Q\n");
halcanary022c2bd2016-09-02 11:29:46 -07001022 }
Hal Canary42137de2018-10-08 16:00:37 -04001023 fNeedsExtraSave = false;
1024 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001025}
1026
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001027/* 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 */
Mike Reeda1361362017-03-07 09:37:29 -05001034bool SkPDFDevice::handleInversePath(const SkPath& origPath,
Robert Phillips137ca522018-08-15 10:14:33 -04001035 const SkPaint& paint,
1036 bool pathIsMutable) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001037 if (!origPath.isInverseFillType()) {
1038 return false;
1039 }
1040
Hal Canaryb4e528d2018-03-09 16:02:15 -05001041 if (this->hasEmptyClip()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001042 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();
Michael Ludwigc89d1b52019-10-18 11:32:56 -04001061 this->internalDrawPath(this->cs(), this->localToDevice(), modifiedPath, paint, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001062 return true;
1063 }
1064 }
1065
1066 // Get bounds of clip in current transform space
1067 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001068 SkMatrix transformInverse;
Michael Ludwigc89d1b52019-10-18 11:32:56 -04001069 SkMatrix totalMatrix = this->localToDevice();
Robert Phillips137ca522018-08-15 10:14:33 -04001070
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001071 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001072 return false;
1073 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001074 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001075 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
Michael Ludwigc89d1b52019-10-18 11:32:56 -04001086 this->internalDrawPath(this->cs(), this->localToDevice(), modifiedPath, noInversePaint, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001087 return true;
1088}
1089
Hal Canary6028fa72019-04-10 15:33:06 -04001090SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(SkIRect bounds, bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001091 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001092 if (!fInitialTransform.isIdentity()) {
1093 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001094 SkDEBUGFAIL("Layer initial transform should be invertible.");
1095 inverseTransform.reset();
1096 }
1097 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001098 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
Hal Canarye650b852018-09-12 09:12:36 -04001099
Hal Canary9a3f5542018-12-10 19:59:07 -05001100 SkPDFIndirectReference xobject =
1101 SkPDFMakeFormXObject(fDocument, this->content(),
Hal Canary6028fa72019-04-10 15:33:06 -04001102 SkPDFMakeArray(bounds.left(), bounds.top(),
1103 bounds.right(), bounds.bottom()),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001104 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001105 // 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.
Hal Canary9e41c212018-09-03 12:00:23 -04001108 this->reset();
reed@google.comfc641d02012-09-20 17:52:20 +00001109 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001110}
1111
Hal Canary6028fa72019-04-10 15:33:06 -04001112SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
1113 return this->makeFormXObjectFromDevice(SkIRect{0, 0, this->width(), this->height()}, alpha);
1114}
1115
Hal Canary9a3f5542018-12-10 19:59:07 -05001116void SkPDFDevice::drawFormXObjectWithMask(SkPDFIndirectReference xObject,
1117 SkPDFIndirectReference sMask,
reed374772b2016-10-05 17:33:02 -07001118 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001119 bool invertClip) {
Hal Canary9a3f5542018-12-10 19:59:07 -05001120 SkASSERT(sMask);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001121 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001122 paint.setBlendMode(mode);
Hal Canaryd892a9d2018-09-24 21:20:47 -04001123 ScopedContentEntry content(this, nullptr, SkMatrix::I(), paint);
Hal Canary42137de2018-10-08 16:00:37 -04001124 if (!content) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001125 return;
1126 }
Hal Canary3b8b11e2018-09-29 22:31:34 -04001127 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
Hal Canary9a3f5542018-12-10 19:59:07 -05001128 sMask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode,
1129 fDocument), content.stream());
1130 this->drawFormXObject(xObject, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001131 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001132}
1133
Hal Canaryb400d4d2018-09-26 16:33:52 -04001134
1135static bool treat_as_regular_pdf_blend_mode(SkBlendMode blendMode) {
1136 return nullptr != SkPDFUtils::BlendModeName(blendMode);
1137}
1138
Hal Canary8f37ce52018-12-28 11:40:10 -05001139static 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,
Hal Canaryf5edf362019-04-10 11:00:01 -04001147 SkPDFGraphicStackState::Entry* entry,
Hal Canary8f37ce52018-12-28 11:40:10 -05001148 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) {
Mike Reedb9c98292021-06-15 09:37:20 -04001164 // 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)
Hal Canary8f37ce52018-12-28 11:40:10 -05001166 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
Mike Reedb9c98292021-06-15 09:37:20 -04001194 auto c = paint.getColor4f();
1195 SkPDFIndirectReference pdfShader = SkPDFMakeShader(doc, shader, transform, bounds,
1196 {c.fR, c.fG, c.fB, 1.0f});
Hal Canary8f37ce52018-12-28 11:40:10 -05001197
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
Hal Canaryb400d4d2018-09-26 16:33:52 -04001217SkDynamicMemoryWStream* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1218 const SkMatrix& matrix,
1219 const SkPaint& paint,
Hal Canary8f37ce52018-12-28 11:40:10 -05001220 SkScalar textScale,
Hal Canary9a3f5542018-12-10 19:59:07 -05001221 SkPDFIndirectReference* dst) {
1222 SkASSERT(!*dst);
Mike Reed90f4e9f2021-07-07 16:05:25 -04001223 SkBlendMode blendMode = paint.getBlendMode_or(SkBlendMode::kSrcOver);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001224
Hal Canaryb400d4d2018-09-26 16:33:52 -04001225 // Dst xfer mode doesn't draw source at all.
1226 if (blendMode == SkBlendMode::kDst) {
1227 return nullptr;
1228 }
1229
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001230 // For the following modes, we want to handle source and destination
1231 // separately, so make an object of what's already there.
Hal Canaryb400d4d2018-09-26 16:33:52 -04001232 if (!treat_as_regular_pdf_blend_mode(blendMode) && blendMode != SkBlendMode::kDstOver) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001233 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001234 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001235 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001236 } else if (blendMode != SkBlendMode::kSrc &&
1237 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001238 // Except for Src and SrcOut, if there isn't anything already there,
1239 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001240 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001241 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001242 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001243 // TODO(vandebo): Figure out how/if we can handle the following modes:
Hal Canaryb400d4d2018-09-26 16:33:52 -04001244 // Xor, Plus. For now, we treat them as SrcOver/Normal.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001245
Hal Canaryb400d4d2018-09-26 16:33:52 -04001246 if (treat_as_regular_pdf_blend_mode(blendMode)) {
1247 if (!fActiveStackState.fContentStream) {
Hal Canary42137de2018-10-08 16:00:37 -04001248 if (fContent.bytesWritten() != 0) {
1249 fContent.writeText("Q\nq\n");
1250 fNeedsExtraSave = true;
1251 }
Hal Canaryf5edf362019-04-10 11:00:01 -04001252 fActiveStackState = SkPDFGraphicStackState(&fContent);
Hal Canary42137de2018-10-08 16:00:37 -04001253 } else {
1254 SkASSERT(fActiveStackState.fContentStream = &fContent);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001255 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001256 } else {
Hal Canaryb400d4d2018-09-26 16:33:52 -04001257 fActiveStackState.drainStack();
Hal Canaryf5edf362019-04-10 11:00:01 -04001258 fActiveStackState = SkPDFGraphicStackState(&fContentBuffer);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001259 }
Hal Canaryb400d4d2018-09-26 16:33:52 -04001260 SkASSERT(fActiveStackState.fContentStream);
Hal Canaryf5edf362019-04-10 11:00:01 -04001261 SkPDFGraphicStackState::Entry entry;
Hal Canary8f37ce52018-12-28 11:40:10 -05001262 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);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001273 fActiveStackState.updateClip(clipStack, this->bounds());
1274 fActiveStackState.updateMatrix(entry.fMatrix);
1275 fActiveStackState.updateDrawingState(entry);
1276
1277 return fActiveStackState.fContentStream;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001278}
1279
Hal Canaryb400d4d2018-09-26 16:33:52 -04001280void SkPDFDevice::finishContentEntry(const SkClipStack* clipStack,
1281 SkBlendMode blendMode,
Hal Canary9a3f5542018-12-10 19:59:07 -05001282 SkPDFIndirectReference dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001283 SkPath* shape) {
Hal Canaryb400d4d2018-09-26 16:33:52 -04001284 SkASSERT(blendMode != SkBlendMode::kDst);
1285 if (treat_as_regular_pdf_blend_mode(blendMode)) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001286 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001287 return;
1288 }
Hal Canaryb400d4d2018-09-26 16:33:52 -04001289
1290 SkASSERT(fActiveStackState.fContentStream);
1291
1292 fActiveStackState.drainStack();
Hal Canaryf5edf362019-04-10 11:00:01 -04001293 fActiveStackState = SkPDFGraphicStackState();
Hal Canaryb400d4d2018-09-26 16:33:52 -04001294
reed374772b2016-10-05 17:33:02 -07001295 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001296 SkASSERT(!dst);
Hal Canary42137de2018-10-08 16:00:37 -04001297 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);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001304 }
1305 return;
1306 }
Hal Canary42137de2018-10-08 16:00:37 -04001307 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
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001316 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001317 SkASSERT(blendMode == SkBlendMode::kSrc ||
1318 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001319 return;
1320 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001321
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001322 SkASSERT(dst);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001323 // 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.
halcanary2be7e012016-03-28 11:58:08 -07001327
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001328 SkPaint stockPaint;
1329
Hal Canary9a3f5542018-12-10 19:59:07 -05001330 SkPDFIndirectReference srcFormXObject;
Hal Canary9e41c212018-09-03 12:00:23 -04001331 if (this->isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001332 // 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.
reed374772b2016-10-05 17:33:02 -07001337 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1338 blendMode == SkBlendMode::kSrcATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001339 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary9a3f5542018-12-10 19:59:07 -05001340 this->drawFormXObject(dst, content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001341 return;
1342 } else {
reed374772b2016-10-05 17:33:02 -07001343 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001344 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001345 } else {
halcanary4b1e17e2016-07-27 14:49:46 -07001346 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001347 }
1348
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001349 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1350 // without alpha.
reed374772b2016-10-05 17:33:02 -07001351 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001352 // 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.
Hal Canaryc4c41c92018-09-28 13:30:45 -04001356 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001357 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001358 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001359 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001360 SkPaint filledPaint;
1361 filledPaint.setColor(SK_ColorBLACK);
1362 filledPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001363 SkClipStack empty;
Hal Canary813b5ac2018-09-28 12:30:37 -04001364 SkPDFDevice shapeDev(this->size(), fDocument, fInitialTransform);
1365 shapeDev.internalDrawPath(clipStack ? *clipStack : empty,
1366 SkMatrix::I(), *shape, filledPaint, true);
Hal Canaryc4c41c92018-09-28 13:30:45 -04001367 this->drawFormXObjectWithMask(dst, shapeDev.makeFormXObjectFromDevice(),
Mike Reeda1361362017-03-07 09:37:29 -05001368 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07001369 } else {
Hal Canaryc4c41c92018-09-28 13:30:45 -04001370 this->drawFormXObjectWithMask(dst, srcFormXObject, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001371 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001372 }
1373
reed374772b2016-10-05 17:33:02 -07001374 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001375 return;
reed374772b2016-10-05 17:33:02 -07001376 } else if (blendMode == SkBlendMode::kSrc ||
1377 blendMode == SkBlendMode::kDstATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001378 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary42137de2018-10-08 16:00:37 -04001379 if (content) {
Hal Canary3b8b11e2018-09-29 22:31:34 -04001380 this->drawFormXObject(srcFormXObject, content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001381 }
reed374772b2016-10-05 17:33:02 -07001382 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001383 return;
1384 }
reed374772b2016-10-05 17:33:02 -07001385 } else if (blendMode == SkBlendMode::kSrcATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001386 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary42137de2018-10-08 16:00:37 -04001387 if (content) {
Hal Canary3b8b11e2018-09-29 22:31:34 -04001388 this->drawFormXObject(dst, content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001389 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001390 }
1391
reed374772b2016-10-05 17:33:02 -07001392 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);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001399
reed374772b2016-10-05 17:33:02 -07001400 if (blendMode == SkBlendMode::kSrcIn ||
1401 blendMode == SkBlendMode::kSrcOut ||
1402 blendMode == SkBlendMode::kSrcATop) {
Hal Canary9a3f5542018-12-10 19:59:07 -05001403 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver,
1404 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001405 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001406 } else {
reed374772b2016-10-05 17:33:02 -07001407 SkBlendMode mode = SkBlendMode::kSrcOver;
reed374772b2016-10-05 17:33:02 -07001408 if (blendMode == SkBlendMode::kModulate) {
Hal Canaryc4c41c92018-09-28 13:30:45 -04001409 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, false);
reed374772b2016-10-05 17:33:02 -07001410 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001411 }
Hal Canary9a3f5542018-12-10 19:59:07 -05001412 this->drawFormXObjectWithMask(dst, srcFormXObject, mode, blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001413 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001414 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001415}
1416
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001417bool SkPDFDevice::isContentEmpty() {
Hal Canary42137de2018-10-08 16:00:37 -04001418 return fContent.bytesWritten() == 0 && fContentBuffer.bytesWritten() == 0;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001419}
1420
Hal Canaryfafe1352017-04-11 12:12:02 -04001421static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07001422
Hal Canary7cbf5e32017-07-12 13:10:23 -04001423static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07001424 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07001425 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04001426 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07001427 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07001428 SkCanvas* canvas = surface->getCanvas();
1429 canvas->clear(SK_ColorTRANSPARENT);
1430 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07001431 paint.setColorFilter(sk_ref_sp(colorFilter));
Mike Reed34c56a52021-01-22 15:26:41 -05001432 canvas->drawImage(image, 0, 0, SkSamplingOptions(), &paint);
halcanarya50151d2016-03-25 11:57:49 -07001433 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07001434}
1435
1436////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04001437
1438static bool is_integer(SkScalar x) {
1439 return x == SkScalarTruncToScalar(x);
1440}
1441
1442static 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
1449void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
1450 const SkRect* src,
1451 const SkRect& dst,
Mike Reedd8ff3132021-01-02 12:57:04 -05001452 const SkSamplingOptions& sampling,
Hal Canary7cbf5e32017-07-12 13:10:23 -04001453 const SkPaint& srcPaint,
1454 const SkMatrix& ctm) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001455 if (this->hasEmptyClip()) {
1456 return;
1457 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001458 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07001459 return;
1460 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001461
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001462 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001463 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04001464 SkRect srcRect = src ? *src : SkRect::Make(bounds);
Mike Reed2ac6ce82021-01-15 12:26:22 -05001465 SkMatrix transform = SkMatrix::RectToRect(srcRect, dst);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001466 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
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001481 // If the image is opaque and the paint's alpha is too, replace
Hal Canarycfb0e022019-04-08 11:52:55 -04001482 // kSrc blendmode with kSrcOver. http://crbug.com/473572
1483 SkTCopyOnFirstWrite<SkPaint> paint(srcPaint);
Mike Reed90f4e9f2021-07-07 16:05:25 -04001484 if (!paint->isSrcOver() &&
Hal Canarycfb0e022019-04-08 11:52:55 -04001485 imageSubset.image()->isOpaque() &&
1486 kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false))
1487 {
1488 paint.writable()->setBlendMode(SkBlendMode::kSrcOver);
Hal Canaryd425a1d2017-07-12 13:13:51 -04001489 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001490
1491 // Alpha-only images need to get their color from the shader, before
1492 // applying the colorfilter.
Hal Canarycfb0e022019-04-08 11:52:55 -04001493 if (imageSubset.image()->isAlphaOnly() && paint->getColorFilter()) {
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001494 // 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.
Hal Canarycfb0e022019-04-08 11:52:55 -04001501 tmpPaint.setShader(sk_ref_sp(paint->getShader()));
1502 tmpPaint.setColor4f(paint->getColor4f(), nullptr);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001503 canvas->clear(0x00000000);
Mike Reedd8ff3132021-01-02 12:57:04 -05001504 canvas->drawImage(imageSubset.image().get(), 0, 0, sampling, &tmpPaint);
Hal Canarycfb0e022019-04-08 11:52:55 -04001505 if (paint->getShader() != nullptr) {
1506 paint.writable()->setShader(nullptr);
1507 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001508 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.
Hal Canarycfb0e022019-04-08 11:52:55 -04001514 SkASSERT(nullptr == paint->getColorFilter());
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001515
Hal Canaryd425a1d2017-07-12 13:13:51 -04001516 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 {
Herb Derbyefe39bc2018-05-01 17:06:20 -04001524 SkCanvas canvas(maskDevice);
Hal Canary6028fa72019-04-10 15:33:06 -04001525 // 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);
Hal Canarycfb0e022019-04-08 11:52:55 -04001529 if (paint->getMaskFilter()) {
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001530 SkPaint tmpPaint;
Mike Reed99c94462020-12-08 13:16:56 -05001531 tmpPaint.setShader(mask->makeShader(SkSamplingOptions(), transform));
Hal Canarycfb0e022019-04-08 11:52:55 -04001532 tmpPaint.setMaskFilter(sk_ref_sp(paint->getMaskFilter()));
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001533 canvas.drawRect(dst, tmpPaint);
1534 } else {
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001535 if (src && !is_integral(*src)) {
1536 canvas.clipRect(dst);
1537 }
1538 canvas.concat(transform);
1539 canvas.drawImage(mask, 0, 0);
1540 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04001541 }
Hal Canary6028fa72019-04-10 15:33:06 -04001542 SkIRect maskDeviceBounds = maskDevice->cs().bounds(maskDevice->bounds()).roundOut();
Hal Canarycfb0e022019-04-08 11:52:55 -04001543 if (!ctm.isIdentity() && paint->getShader()) {
1544 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
Hal Canaryd425a1d2017-07-12 13:13:51 -04001545 }
Hal Canarycfb0e022019-04-08 11:52:55 -04001546 ScopedContentEntry content(this, &this->cs(), SkMatrix::I(), *paint);
Hal Canary42137de2018-10-08 16:00:37 -04001547 if (!content) {
Hal Canaryd425a1d2017-07-12 13:13:51 -04001548 return;
1549 }
Hal Canary6028fa72019-04-10 15:33:06 -04001550 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
1551 maskDevice->makeFormXObjectFromDevice(maskDeviceBounds, true), false,
1552 SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), content.stream());
Hal Canary813b5ac2018-09-28 12:30:37 -04001553 SkPDFUtils::AppendRectangle(SkRect::Make(this->size()), content.stream());
Mike Reed7d34dc72019-11-26 12:17:17 -05001554 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPathFillType::kWinding, content.stream());
Hal Canaryd425a1d2017-07-12 13:13:51 -04001555 this->clearMaskOnGraphicState(content.stream());
1556 return;
1557 }
Hal Canarycfb0e022019-04-08 11:52:55 -04001558 if (paint->getMaskFilter()) {
Mike Reed99c94462020-12-08 13:16:56 -05001559 paint.writable()->setShader(imageSubset.image()->makeShader(SkSamplingOptions(),
1560 transform));
Mike Reed58cc97a2020-08-24 15:15:01 -04001561 SkPath path = SkPath::Rect(dst); // handles non-integral clipping.
Michael Ludwigc89d1b52019-10-18 11:32:56 -04001562 this->internalDrawPath(this->cs(), this->localToDevice(), path, *paint, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001563 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
Hal Canary7cbf5e32017-07-12 13:10:23 -04001576 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001577
1578 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001579 if (transform.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001580 // Transform the bitmap in the new space, without taking into
1581 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001582 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
Mike Reed58cc97a2020-08-24 15:15:01 -04001583 SkPath perspectiveOutline = SkPath::Rect(imageBounds).makeTransform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001584
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001585 // Retrieve the bounds of the new shape.
John Stiles0e157692021-08-02 15:49:20 -04001586 SkRect outlineBounds = perspectiveOutline.getBounds();
1587 if (!outlineBounds.intersect(SkRect::Make(this->devClipBounds()))) {
Michael Ludwig30378382020-10-08 16:29:14 -04001588 return;
1589 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001590
Michael Ludwig30378382020-10-08 16:29:14 -04001591 // Transform the bitmap in the new space to the final space, to account for DPI
John Stiles0e157692021-08-02 15:49:20 -04001592 SkRect physicalBounds = fInitialTransform.mapRect(outlineBounds);
1593 SkScalar scaleX = physicalBounds.width() / outlineBounds.width();
1594 SkScalar scaleY = physicalBounds.height() / outlineBounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001595
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
Michael Ludwig30378382020-10-08 16:29:14 -04001603 SkISize wh = rect_to_size(physicalBounds).toCeil();
halcanary7a14b312015-10-01 07:28:13 -07001604
Hal Canaryf50ff392016-09-30 10:25:39 -04001605 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07001606 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00001607 return;
1608 }
halcanary7a14b312015-10-01 07:28:13 -07001609 SkCanvas* canvas = surface->getCanvas();
1610 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001611
John Stiles0e157692021-08-02 15:49:20 -04001612 SkScalar deltaX = outlineBounds.left();
1613 SkScalar deltaY = outlineBounds.top();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001614
Hal Canary7cbf5e32017-07-12 13:10:23 -04001615 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001616 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001617 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001618
1619 // Translate the draw in the new canvas, so we perfectly fit the
1620 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07001621 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001622 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001623 // Make sure the final bits are in the bitmap.
Greg Daniel0a2464f2020-05-14 15:45:44 -04001624 surface->flushAndSubmit();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001625
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001626 // 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
Hal Canary7cbf5e32017-07-12 13:10:23 -04001631 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1632 if (!imageSubset) {
1633 return;
1634 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001635 }
1636
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001637 SkMatrix scaled;
1638 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001639 scaled.setScale(SK_Scalar1, -SK_Scalar1);
1640 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001641 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001642 SkIRect subset = imageSubset.image()->bounds();
1643 scaled.postScale(SkIntToScalar(subset.width()),
1644 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001645 scaled.postConcat(matrix);
Hal Canarycfb0e022019-04-08 11:52:55 -04001646 ScopedContentEntry content(this, &this->cs(), scaled, *paint);
Hal Canary42137de2018-10-08 16:00:37 -04001647 if (!content) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001648 return;
1649 }
1650 if (content.needShape()) {
Mike Reed58cc97a2020-08-24 15:15:01 -04001651 SkPath shape = SkPath::Rect(SkRect::Make(subset)).makeTransform(matrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001652 content.setShape(shape);
1653 }
1654 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001655 return;
1656 }
1657
Hal Canarycfb0e022019-04-08 11:52:55 -04001658 if (SkColorFilter* colorFilter = paint->getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04001659 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
1660 imageSubset = SkKeyedImage(std::move(img));
1661 if (!imageSubset) {
1662 return;
1663 }
halcanary7a14b312015-10-01 07:28:13 -07001664 // TODO(halcanary): de-dupe this by caching filtered images.
1665 // (maybe in the resource cache?)
1666 }
halcanarya50151d2016-03-25 11:57:49 -07001667
Hal Canary7cbf5e32017-07-12 13:10:23 -04001668 SkBitmapKey key = imageSubset.key();
Hal Canary4ca9fa32018-12-21 16:15:01 -05001669 SkPDFIndirectReference* pdfimagePtr = fDocument->fPDFBitmapMap.find(key);
Hal Canary9a3f5542018-12-10 19:59:07 -05001670 SkPDFIndirectReference pdfimage = pdfimagePtr ? *pdfimagePtr : SkPDFIndirectReference();
1671 if (!pdfimagePtr) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04001672 SkASSERT(imageSubset);
Hal Canary9a3f5542018-12-10 19:59:07 -05001673 pdfimage = SkPDFSerializeImage(imageSubset.image().get(), fDocument,
Hal Canarya1211832018-11-13 16:45:14 -05001674 fDocument->metadata().fEncodingQuality);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001675 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary4ca9fa32018-12-21 16:15:01 -05001676 fDocument->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07001677 }
Hal Canary9a3f5542018-12-10 19:59:07 -05001678 SkASSERT(pdfimage != SkPDFIndirectReference());
1679 this->drawFormXObject(pdfimage, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001680}
reede51c3562016-07-19 14:33:20 -07001681
1682///////////////////////////////////////////////////////////////////////////////////////////////////
1683
reede51c3562016-07-19 14:33:20 -07001684
Mike Reedd8ff3132021-01-02 12:57:04 -05001685void SkPDFDevice::drawDevice(SkBaseDevice* device, const SkSamplingOptions& sampling,
1686 const SkPaint& paint) {
Michael Ludwig278263d2020-10-12 19:49:24 +00001687 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)) {
Mike Reedd8ff3132021-01-02 12:57:04 -05001695 this->INHERITED::drawDevice(device, sampling, paint);
Michael Ludwig278263d2020-10-12 19:49:24 +00001696 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
1722void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, const SkMatrix& localToDevice,
Mike Reedd8ff3132021-01-02 12:57:04 -05001723 const SkSamplingOptions& sampling, const SkPaint& paint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001724 if (this->hasEmptyClip()) {
1725 return;
1726 }
reede51c3562016-07-19 14:33:20 -07001727 SkASSERT(!srcImg->isTextureBacked());
Michael Ludwig16d5b0a2020-08-31 13:07:16 -04001728 SkASSERT(!paint.getMaskFilter() && !paint.getImageFilter());
Florin Malita53f77bd2017-04-28 13:48:37 -04001729
reede51c3562016-07-19 14:33:20 -07001730 SkBitmap resultBM;
Michael Ludwig16d5b0a2020-08-31 13:07:16 -04001731 if (srcImg->getROPixels(&resultBM)) {
Michael Ludwig278263d2020-10-12 19:49:24 +00001732 auto r = SkRect::MakeWH(resultBM.width(), resultBM.height());
Mike Reedd8ff3132021-01-02 12:57:04 -05001733 this->internalDrawImageRect(SkKeyedImage(resultBM), nullptr, r, sampling, paint,
1734 localToDevice);
reede51c3562016-07-19 14:33:20 -07001735 }
1736}
1737
1738sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
Chris Daltonf5b87f92021-04-19 17:27:09 -06001739 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap, this->surfaceProps());
reede51c3562016-07-19 14:33:20 -07001740}
1741
1742sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Chris Daltonf5b87f92021-04-19 17:27:09 -06001743 return SkSpecialImage::MakeFromImage(nullptr, image->bounds(), image->makeNonTextureImage(),
1744 this->surfaceProps());
reede51c3562016-07-19 14:33:20 -07001745}
1746
brianosman04a44d02016-09-21 09:46:57 -07001747SkImageFilterCache* 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}