Debian Codegraph @

src/pdf/SkPDFDevice.cpp

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