2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkPDFDevice.h"
10 #include "SkAdvancedTypefaceMetrics.h"
11 #include "SkAnnotationKeys.h"
12 #include "SkBitmapDevice.h"
13 #include "SkBitmapKey.h"
15 #include "SkColorFilter.h"
17 #include "SkDrawFilter.h"
18 #include "SkGlyphCache.h"
19 #include "SkImageFilterCache.h"
20 #include "SkMakeUnique.h"
22 #include "SkPathEffect.h"
23 #include "SkPathOps.h"
24 #include "SkPDFBitmap.h"
25 #include "SkPDFCanon.h"
26 #include "SkPDFDocument.h"
27 #include "SkPDFFont.h"
28 #include "SkPDFFormXObject.h"
29 #include "SkPDFGraphicState.h"
30 #include "SkPDFResourceDict.h"
31 #include "SkPDFShader.h"
32 #include "SkPDFTypes.h"
33 #include "SkPDFUtils.h"
34 #include "SkPixelRef.h"
35 #include "SkRasterClip.h"
37 #include "SkScopeExit.h"
39 #include "SkSurface.h"
40 #include "SkTemplates.h"
41 #include "SkTextBlobRunIterator.h"
42 #include "SkTextFormatParams.h"
44 #include "SkXfermodeInterpretation.h"
46 #define DPI_FOR_RASTER_SCALE_ONE 72
50 // If the paint will definitely draw opaquely, replace kSrc with
51 // kSrcOver. http://crbug.com/473572
52 static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
53 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
54 paint->setBlendMode(SkBlendMode::kSrcOver);
58 static void emit_pdf_color(SkColor color, SkWStream* result) {
59 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
60 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
61 result->writeText(" ");
62 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
63 result->writeText(" ");
64 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
65 result->writeText(" ");
68 static SkPaint calculate_text_paint(const SkPaint& paint) {
69 SkPaint result = paint;
70 if (result.isFakeBoldText()) {
71 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
72 kStdFakeBoldInterpKeys,
73 kStdFakeBoldInterpValues,
74 kStdFakeBoldInterpLength);
75 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
76 if (result.getStyle() == SkPaint::kFill_Style) {
77 result.setStyle(SkPaint::kStrokeAndFill_Style);
79 width += result.getStrokeWidth();
81 result.setStrokeWidth(width);
86 static SkImageSubset make_image_subset(const SkBitmap& bitmap) {
87 SkASSERT(!bitmap.drawsNothing());
88 SkIRect subset = bitmap.getSubset();
89 SkAutoLockPixels autoLockPixels(bitmap);
90 SkASSERT(bitmap.pixelRef());
92 tmp.setInfo(bitmap.pixelRef()->info(), bitmap.rowBytes());
93 tmp.setPixelRef(bitmap.pixelRef());
95 auto img = SkImage::MakeFromBitmap(tmp);
97 SkASSERT(!bitmap.isImmutable() || img->uniqueID() == bitmap.getGenerationID());
98 SkASSERT(img->bounds().contains(subset));
100 SkImageSubset imageSubset(std::move(img), subset);
101 // SkImage::MakeFromBitmap only preserves genID for immutable
102 // bitmaps. Use the bitmap's original ID for de-duping.
103 imageSubset.setID(bitmap.getGenerationID());
107 SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
108 : fColor(SK_ColorBLACK)
109 , fTextScaleX(SK_Scalar1)
110 , fTextFill(SkPaint::kFill_Style)
112 , fGraphicStateIndex(-1) {
116 bool SkPDFDevice::GraphicStateEntry::compareInitialState(
117 const GraphicStateEntry& cur) {
118 return fColor == cur.fColor &&
119 fShaderIndex == cur.fShaderIndex &&
120 fGraphicStateIndex == cur.fGraphicStateIndex &&
121 fMatrix == cur.fMatrix &&
122 fClipStack == cur.fClipStack &&
124 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
127 class GraphicStackState {
129 GraphicStackState(const SkClipStack& existingClipStack,
130 const SkRegion& existingClipRegion,
131 SkWStream* contentStream)
133 fContentStream(contentStream) {
134 fEntries[0].fClipStack = existingClipStack;
135 fEntries[0].fClipRegion = existingClipRegion;
138 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
139 const SkPoint& translation);
140 void updateMatrix(const SkMatrix& matrix);
141 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
148 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
150 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
151 static const int kMaxStackDepth = 12;
152 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
154 SkWStream* fContentStream;
157 void GraphicStackState::drainStack() {
158 while (fStackDepth) {
163 void GraphicStackState::push() {
164 SkASSERT(fStackDepth < kMaxStackDepth);
165 fContentStream->writeText("q\n");
167 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
170 void GraphicStackState::pop() {
171 SkASSERT(fStackDepth > 0);
172 fContentStream->writeText("Q\n");
176 /* Calculate an inverted path's equivalent non-inverted path, given the
178 * outPath may alias with invPath (since this is supported by PathOps).
180 static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
182 SkASSERT(invPath.isInverseFillType());
185 clipPath.addRect(bounds);
187 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
190 // Sanity check the numerical values of the SkRegion ops and PathOps ops
191 // enums so region_op_to_pathops_op can do a straight passthrough cast.
192 // If these are failing, it may be necessary to make region_op_to_pathops_op
194 static_assert(SkRegion::kDifference_Op == (int)kDifference_SkPathOp, "region_pathop_mismatch");
195 static_assert(SkRegion::kIntersect_Op == (int)kIntersect_SkPathOp, "region_pathop_mismatch");
196 static_assert(SkRegion::kUnion_Op == (int)kUnion_SkPathOp, "region_pathop_mismatch");
197 static_assert(SkRegion::kXOR_Op == (int)kXOR_SkPathOp, "region_pathop_mismatch");
198 static_assert(SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkPathOp,
199 "region_pathop_mismatch");
201 static SkPathOp region_op_to_pathops_op(SkClipOp op) {
203 SkASSERT(op <= kReverseDifference_SkClipOp);
207 /* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
208 * Returns true if successful, or false if not successful.
209 * If successful, the resulting clip is stored in outClipPath.
210 * If not successful, outClipPath is undefined, and a fallback method
213 static bool get_clip_stack_path(const SkMatrix& transform,
214 const SkClipStack& clipStack,
215 const SkRegion& clipRegion,
216 SkPath* outClipPath) {
217 outClipPath->reset();
218 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
220 const SkClipStack::Element* clipEntry;
221 SkClipStack::Iter iter;
222 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
223 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
225 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
226 outClipPath->reset();
227 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
230 clipEntry->asPath(&entryPath);
232 entryPath.transform(transform);
234 if (kReplace_SkClipOp == clipEntry->getOp()) {
235 *outClipPath = entryPath;
237 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
238 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
244 if (outClipPath->isInverseFillType()) {
245 // The bounds are slightly outset to ensure this is correct in the
246 // face of floating-point accuracy and possible SkRegion bitmap
248 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
249 clipBounds.outset(SK_Scalar1, SK_Scalar1);
250 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
257 // TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
258 // graphic state stack, and the fact that we can know all the clips used
259 // on the page to optimize this.
260 void GraphicStackState::updateClip(const SkClipStack& clipStack,
261 const SkRegion& clipRegion,
262 const SkPoint& translation) {
263 if (clipStack == currentEntry()->fClipStack) {
267 while (fStackDepth > 0) {
269 if (clipStack == currentEntry()->fClipStack) {
275 currentEntry()->fClipStack = clipStack;
276 currentEntry()->fClipRegion = clipRegion;
279 transform.setTranslate(translation.fX, translation.fY);
282 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
283 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
284 SkPath::FillType clipFill = clipPath.getFillType();
285 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
286 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
287 if (clipFill == SkPath::kEvenOdd_FillType) {
288 fContentStream->writeText("W* n\n");
290 fContentStream->writeText("W n\n");
293 // If Op() fails (pathological case; e.g. input values are
294 // extremely large or NaN), emit no clip at all.
297 void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
298 if (matrix == currentEntry()->fMatrix) {
302 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
303 SkASSERT(fStackDepth > 0);
304 SkASSERT(fEntries[fStackDepth].fClipStack ==
305 fEntries[fStackDepth -1].fClipStack);
308 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
310 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
315 SkPDFUtils::AppendTransform(matrix, fContentStream);
316 currentEntry()->fMatrix = matrix;
319 void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
320 // PDF treats a shader as a color, so we only set one or the other.
321 if (state.fShaderIndex >= 0) {
322 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
323 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
324 currentEntry()->fShaderIndex = state.fShaderIndex;
327 if (state.fColor != currentEntry()->fColor ||
328 currentEntry()->fShaderIndex >= 0) {
329 emit_pdf_color(state.fColor, fContentStream);
330 fContentStream->writeText("RG ");
331 emit_pdf_color(state.fColor, fContentStream);
332 fContentStream->writeText("rg\n");
333 currentEntry()->fColor = state.fColor;
334 currentEntry()->fShaderIndex = -1;
338 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
339 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
340 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
343 if (state.fTextScaleX) {
344 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
345 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
347 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
348 fContentStream->writeText(" Tz\n");
349 currentEntry()->fTextScaleX = state.fTextScaleX;
351 if (state.fTextFill != currentEntry()->fTextFill) {
352 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
353 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
354 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
355 fContentStream->writeDecAsText(state.fTextFill);
356 fContentStream->writeText(" Tr\n");
357 currentEntry()->fTextFill = state.fTextFill;
362 static bool not_supported_for_layers(const SkPaint& layerPaint) {
363 // PDF does not support image filters, so render them on CPU.
364 // Note that this rendering is done at "screen" resolution (100dpi), not
365 // printer resolution.
366 // TODO: It may be possible to express some filters natively using PDF
367 // to improve quality and file size (https://bug.skia.org/3043)
369 // TODO: should we return true if there is a colorfilter?
370 return layerPaint.getImageFilter() != nullptr;
373 SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
374 if (layerPaint && not_supported_for_layers(*layerPaint)) {
375 // need to return a raster device, which we will detect in drawDevice()
376 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
378 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
379 return SkPDFDevice::Create(size, fRasterDpi, fDocument);
382 SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
386 // A helper class to automatically finish a ContentEntry at the end of a
387 // drawing method and maintain the state needed between set up and finish.
388 class ScopedContentEntry {
390 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
391 const SkPaint& paint, bool hasText = false)
393 fContentEntry(nullptr),
394 fBlendMode(SkBlendMode::kSrcOver),
395 fDstFormXObject(nullptr) {
396 init(draw.fClipStack, draw.fRC->bwRgn(), *draw.fMatrix, paint, hasText);
398 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
399 const SkRegion& clipRegion, const SkMatrix& matrix,
400 const SkPaint& paint, bool hasText = false)
402 fContentEntry(nullptr),
403 fBlendMode(SkBlendMode::kSrcOver),
404 fDstFormXObject(nullptr) {
405 init(clipStack, clipRegion, matrix, paint, hasText);
408 ~ScopedContentEntry() {
410 SkPath* shape = &fShape;
411 if (shape->isEmpty()) {
414 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
418 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
420 /* Returns true when we explicitly need the shape of the drawing. */
422 switch (fBlendMode) {
423 case SkBlendMode::kClear:
424 case SkBlendMode::kSrc:
425 case SkBlendMode::kSrcIn:
426 case SkBlendMode::kSrcOut:
427 case SkBlendMode::kDstIn:
428 case SkBlendMode::kDstOut:
429 case SkBlendMode::kSrcATop:
430 case SkBlendMode::kDstATop:
431 case SkBlendMode::kModulate:
438 /* Returns true unless we only need the shape of the drawing. */
440 if (fBlendMode == SkBlendMode::kClear) {
446 /* If the shape is different than the alpha component of the content, then
447 * setShape should be called with the shape. In particular, images and
448 * devices have rectangular shape.
450 void setShape(const SkPath& shape) {
455 SkPDFDevice* fDevice;
456 SkPDFDevice::ContentEntry* fContentEntry;
457 SkBlendMode fBlendMode;
458 sk_sp<SkPDFObject> fDstFormXObject;
461 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
462 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
463 // Shape has to be flatten before we get here.
464 if (matrix.hasPerspective()) {
465 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
468 fBlendMode = paint.getBlendMode();
469 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
470 matrix, paint, hasText,
475 ////////////////////////////////////////////////////////////////////////////////
477 SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
478 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
479 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
480 , fPageSize(pageSize)
481 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
482 , fRasterDpi(rasterDpi)
484 SkASSERT(pageSize.width() > 0);
485 SkASSERT(pageSize.height() > 0);
488 // Skia generally uses the top left as the origin but PDF
489 // natively has the origin at the bottom left. This matrix
490 // corrects for that. But that only needs to be done once, we
491 // don't do it when layering.
492 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
493 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
495 fInitialTransform.setIdentity();
499 SkPDFDevice::~SkPDFDevice() {
503 void SkPDFDevice::init() {
504 fContentEntries.reset();
507 void SkPDFDevice::cleanUp() {
508 fGraphicStateResources.unrefAll();
509 fXObjectResources.unrefAll();
510 fFontResources.unrefAll();
511 fShaderResources.unrefAll();
514 void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
516 if (0 == rect.width() && 0 == rect.height()) {
517 handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
521 handlePathAnnotation(path, d, key, value);
525 void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
526 SkPaint newPaint = paint;
527 replace_srcmode_on_opaque_paint(&newPaint);
529 newPaint.setStyle(SkPaint::kFill_Style);
530 ScopedContentEntry content(this, d, newPaint);
531 internalDrawPaint(newPaint, content.entry());
534 void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
535 SkPDFDevice::ContentEntry* contentEntry) {
539 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
540 SkIntToScalar(this->height()));
542 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
545 inverse.mapRect(&bbox);
547 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
548 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
549 &contentEntry->fContent);
552 void SkPDFDevice::drawPoints(const SkDraw& d,
553 SkCanvas::PointMode mode,
555 const SkPoint* points,
556 const SkPaint& srcPaint) {
557 SkPaint passedPaint = srcPaint;
558 replace_srcmode_on_opaque_paint(&passedPaint);
564 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
565 // We only use this when there's a path effect because of the overhead
566 // of multiple calls to setUpContentEntry it causes.
567 if (passedPaint.getPathEffect()) {
568 if (d.fRC->isEmpty()) {
572 pointDraw.fDevice = this;
573 pointDraw.drawPoints(mode, count, points, passedPaint, true);
577 const SkPaint* paint = &passedPaint;
578 SkPaint modifiedPaint;
580 if (mode == SkCanvas::kPoints_PointMode &&
581 paint->getStrokeCap() != SkPaint::kRound_Cap) {
582 modifiedPaint = *paint;
583 paint = &modifiedPaint;
584 if (paint->getStrokeWidth()) {
585 // PDF won't draw a single point with square/butt caps because the
586 // orientation is ambiguous. Draw a rectangle instead.
587 modifiedPaint.setStyle(SkPaint::kFill_Style);
588 SkScalar strokeWidth = paint->getStrokeWidth();
589 SkScalar halfStroke = SkScalarHalf(strokeWidth);
590 for (size_t i = 0; i < count; i++) {
591 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
592 r.inset(-halfStroke, -halfStroke);
593 drawRect(d, r, modifiedPaint);
597 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
601 ScopedContentEntry content(this, d, *paint);
602 if (!content.entry()) {
607 case SkCanvas::kPolygon_PointMode:
608 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
609 &content.entry()->fContent);
610 for (size_t i = 1; i < count; i++) {
611 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
612 &content.entry()->fContent);
614 SkPDFUtils::StrokePath(&content.entry()->fContent);
616 case SkCanvas::kLines_PointMode:
617 for (size_t i = 0; i < count/2; i++) {
618 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
619 &content.entry()->fContent);
620 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
621 points[i * 2 + 1].fY,
622 &content.entry()->fContent);
623 SkPDFUtils::StrokePath(&content.entry()->fContent);
626 case SkCanvas::kPoints_PointMode:
627 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
628 for (size_t i = 0; i < count; i++) {
629 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
630 &content.entry()->fContent);
631 SkPDFUtils::ClosePath(&content.entry()->fContent);
632 SkPDFUtils::StrokePath(&content.entry()->fContent);
640 static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
641 auto annotation = sk_make_sp<SkPDFDict>("Annot");
642 annotation->insertName("Subtype", "Link");
643 annotation->insertInt("F", 4); // required by ISO 19005
645 auto border = sk_make_sp<SkPDFArray>();
647 border->appendInt(0); // Horizontal corner radius.
648 border->appendInt(0); // Vertical corner radius.
649 border->appendInt(0); // Width, 0 = no border.
650 annotation->insertObject("Border", std::move(border));
652 auto rect = sk_make_sp<SkPDFArray>();
654 rect->appendScalar(translatedRect.fLeft);
655 rect->appendScalar(translatedRect.fTop);
656 rect->appendScalar(translatedRect.fRight);
657 rect->appendScalar(translatedRect.fBottom);
658 annotation->insertObject("Rect", std::move(rect));
663 static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
664 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
665 SkString url(static_cast<const char *>(urlData->data()),
666 urlData->size() - 1);
667 auto action = sk_make_sp<SkPDFDict>("Action");
668 action->insertName("S", "URI");
669 action->insertString("URI", url);
670 annotation->insertObject("A", std::move(action));
674 static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
676 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
677 SkString name(static_cast<const char *>(nameData->data()),
678 nameData->size() - 1);
679 annotation->insertName("Dest", name);
683 void SkPDFDevice::drawRect(const SkDraw& d,
685 const SkPaint& srcPaint) {
686 SkPaint paint = srcPaint;
687 replace_srcmode_on_opaque_paint(&paint);
691 if (paint.getPathEffect()) {
692 if (d.fRC->isEmpty()) {
697 drawPath(d, path, paint, nullptr, true);
701 ScopedContentEntry content(this, d, paint);
702 if (!content.entry()) {
705 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
706 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
707 &content.entry()->fContent);
710 void SkPDFDevice::drawRRect(const SkDraw& draw,
711 const SkRRect& rrect,
712 const SkPaint& srcPaint) {
713 SkPaint paint = srcPaint;
714 replace_srcmode_on_opaque_paint(&paint);
716 path.addRRect(rrect);
717 this->drawPath(draw, path, paint, nullptr, true);
720 void SkPDFDevice::drawOval(const SkDraw& draw,
722 const SkPaint& srcPaint) {
723 SkPaint paint = srcPaint;
724 replace_srcmode_on_opaque_paint(&paint);
727 this->drawPath(draw, path, paint, nullptr, true);
730 void SkPDFDevice::drawPath(const SkDraw& d,
731 const SkPath& origPath,
732 const SkPaint& srcPaint,
733 const SkMatrix* prePathMatrix,
734 bool pathIsMutable) {
735 SkPaint paint = srcPaint;
736 replace_srcmode_on_opaque_paint(&paint);
738 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
740 SkMatrix matrix = *d.fMatrix;
742 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
743 if (!pathIsMutable) {
744 pathPtr = &modifiedPath;
745 pathIsMutable = true;
747 origPath.transform(*prePathMatrix, pathPtr);
749 matrix.preConcat(*prePathMatrix);
753 if (paint.getPathEffect()) {
754 if (d.fRC->isEmpty()) {
757 if (!pathIsMutable) {
758 pathPtr = &modifiedPath;
759 pathIsMutable = true;
761 bool fill = paint.getFillPath(origPath, pathPtr);
763 SkPaint noEffectPaint(paint);
764 noEffectPaint.setPathEffect(nullptr);
766 noEffectPaint.setStyle(SkPaint::kFill_Style);
768 noEffectPaint.setStyle(SkPaint::kStroke_Style);
769 noEffectPaint.setStrokeWidth(0);
771 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
775 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
779 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
780 if (!content.entry()) {
783 bool consumeDegeratePathSegments =
784 paint.getStyle() == SkPaint::kFill_Style ||
785 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
786 paint.getStrokeCap() != SkPaint::kSquare_Cap);
787 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
788 consumeDegeratePathSegments,
789 &content.entry()->fContent);
790 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
791 &content.entry()->fContent);
795 void SkPDFDevice::drawImageRect(const SkDraw& d,
796 const SkImage* image,
799 const SkPaint& srcPaint,
800 SkCanvas::SrcRectConstraint) {
804 SkIRect bounds = image->bounds();
805 SkPaint paint = srcPaint;
806 if (image->isOpaque()) {
807 replace_srcmode_on_opaque_paint(&paint);
809 SkRect srcRect = src ? *src : SkRect::Make(bounds);
811 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
813 if (!srcRect.intersect(SkRect::Make(bounds))) {
816 srcRect.roundOut(&bounds);
817 transform.preTranslate(SkIntToScalar(bounds.x()),
818 SkIntToScalar(bounds.y()));
820 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)), bounds);
821 if (!imageSubset.isValid()) {
824 transform.postConcat(*d.fMatrix);
825 this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
826 std::move(imageSubset), paint);
829 void SkPDFDevice::drawBitmapRect(const SkDraw& d,
830 const SkBitmap& bitmap,
833 const SkPaint& srcPaint,
834 SkCanvas::SrcRectConstraint) {
835 if (bitmap.drawsNothing()) {
838 SkIRect bounds = bitmap.bounds();
839 SkPaint paint = srcPaint;
840 if (bitmap.isOpaque()) {
841 replace_srcmode_on_opaque_paint(&paint);
843 SkRect srcRect = src ? *src : SkRect::Make(bounds);
845 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
847 if (!srcRect.intersect(SkRect::Make(bounds))) {
850 srcRect.roundOut(&bounds);
851 transform.preTranslate(SkIntToScalar(bounds.x()),
852 SkIntToScalar(bounds.y()));
854 SkBitmap bitmapSubset;
855 if (!bitmap.extractSubset(&bitmapSubset, bounds)) {
858 SkImageSubset imageSubset = make_image_subset(bitmapSubset);
859 if (!imageSubset.isValid()) {
862 transform.postConcat(*d.fMatrix);
863 this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
864 std::move(imageSubset), paint);
867 void SkPDFDevice::drawBitmap(const SkDraw& d,
868 const SkBitmap& bitmap,
869 const SkMatrix& matrix,
870 const SkPaint& srcPaint) {
871 if (bitmap.drawsNothing() || d.fRC->isEmpty()) {
874 SkPaint paint = srcPaint;
875 if (bitmap.isOpaque()) {
876 replace_srcmode_on_opaque_paint(&paint);
878 SkImageSubset imageSubset = make_image_subset(bitmap);
879 if (!imageSubset.isValid()) {
882 SkMatrix transform = matrix;
883 transform.postConcat(*d.fMatrix);
884 this->internalDrawImage(
885 transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
888 void SkPDFDevice::drawSprite(const SkDraw& d,
889 const SkBitmap& bitmap,
892 const SkPaint& srcPaint) {
893 if (bitmap.drawsNothing() || d.fRC->isEmpty()) {
896 SkPaint paint = srcPaint;
897 if (bitmap.isOpaque()) {
898 replace_srcmode_on_opaque_paint(&paint);
900 SkImageSubset imageSubset = make_image_subset(bitmap);
901 if (!imageSubset.isValid()) {
904 SkMatrix transform = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
905 this->internalDrawImage(
906 transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
909 void SkPDFDevice::drawImage(const SkDraw& draw,
910 const SkImage* image,
913 const SkPaint& srcPaint) {
914 SkPaint paint = srcPaint;
918 if (image->isOpaque()) {
919 replace_srcmode_on_opaque_paint(&paint);
921 if (draw.fRC->isEmpty()) {
924 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)));
925 if (!imageSubset.isValid()) {
928 SkMatrix transform = SkMatrix::MakeTrans(x, y);
929 transform.postConcat(*draw.fMatrix);
930 this->internalDrawImage(
931 transform, draw.fClipStack, draw.fRC->bwRgn(), std::move(imageSubset), paint);
935 class GlyphPositioner {
937 GlyphPositioner(SkDynamicMemoryWStream* content,
940 bool defaultPositioning,
943 , fCurrentMatrixOrigin(origin)
944 , fTextSkewX(textSkewX)
945 , fWideChars(wideChars)
946 , fDefaultPositioning(defaultPositioning) {
948 ~GlyphPositioner() { this->flush(); }
951 fContent->writeText("> Tj\n");
955 void writeGlyph(SkPoint xy,
956 SkScalar advanceWidth,
959 // Flip the text about the x-axis to account for origin swap and include
960 // the passed parameters.
961 fContent->writeText("1 0 ");
962 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
963 fContent->writeText(" -1 ");
964 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
965 fContent->writeText(" ");
966 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
967 fContent->writeText(" Tm\n");
968 fCurrentMatrixOrigin.set(0.0f, 0.0f);
971 #ifdef SK_BUILD_FOR_WIN
972 const bool kAlwaysPosition = true;
974 const bool kAlwaysPosition = false;
976 if (!fDefaultPositioning) {
977 SkPoint position = xy - fCurrentMatrixOrigin;
978 if (kAlwaysPosition || position != SkPoint{fXAdvance, 0}) {
980 SkPDFUtils::AppendScalar(position.x(), fContent);
981 fContent->writeText(" ");
982 SkPDFUtils::AppendScalar(-position.y(), fContent);
983 fContent->writeText(" Td ");
984 fCurrentMatrixOrigin = xy;
987 fXAdvance += advanceWidth;
990 fContent->writeText("<");
994 SkPDFUtils::WriteUInt16BE(fContent, glyph);
996 SkASSERT(0 == glyph >> 8);
997 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1002 SkDynamicMemoryWStream* fContent;
1003 SkPoint fCurrentMatrixOrigin;
1004 SkScalar fXAdvance = 0.0f;
1005 SkScalar fTextSkewX;
1007 bool fInText = false;
1008 bool fInitialized = false;
1009 const bool fDefaultPositioning;
1012 /** Given the m-to-n glyph-to-character mapping data (as returned by
1013 harfbuzz), iterate over the clusters. */
1016 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1017 explicit Clusterator(uint32_t glyphCount)
1018 : fClusters(nullptr)
1019 , fUtf8Text(nullptr)
1020 , fGlyphCount(glyphCount)
1021 , fTextByteLength(0) {}
1022 // The clusters[] array is an array of offsets into utf8Text[],
1023 // one offset for each glyph. See SkTextBlobBuilder for more info.
1024 Clusterator(const uint32_t* clusters,
1025 const char* utf8Text,
1026 uint32_t glyphCount,
1027 uint32_t textByteLength)
1028 : fClusters(clusters)
1029 , fUtf8Text(utf8Text)
1030 , fGlyphCount(glyphCount)
1031 , fTextByteLength(textByteLength) {
1032 // This is a cheap heuristic for /ReversedChars which seems to
1033 // work for clusters produced by HarfBuzz, which either
1034 // increase from zero (LTR) or decrease to zero (RTL).
1035 // "ReversedChars" is how PDF deals with RTL text.
1037 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1040 const char* fUtf8Text;
1041 uint32_t fTextByteLength;
1042 uint32_t fGlyphIndex;
1043 uint32_t fGlyphCount;
1044 explicit operator bool() const { return fGlyphCount != 0; }
1046 // True if this looks like right-to-left text.
1047 bool reversedChars() const { return fReversedChars; }
1049 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1050 // These glyphs have no text. Treat as one "cluster".
1051 uint32_t glyphCount = fGlyphCount;
1053 return Cluster{nullptr, 0, 0, glyphCount};
1055 if (fGlyphCount == 0 || fTextByteLength == 0) {
1056 return Cluster{nullptr, 0, 0, 0}; // empty
1058 SkASSERT(fUtf8Text);
1059 SkASSERT(fClusters);
1060 uint32_t cluster = fClusters[0];
1061 if (cluster >= fTextByteLength) {
1062 return Cluster{nullptr, 0, 0, 0}; // bad input.
1064 uint32_t glyphsInCluster = 1;
1065 while (glyphsInCluster < fGlyphCount &&
1066 fClusters[glyphsInCluster] == cluster) {
1069 SkASSERT(glyphsInCluster <= fGlyphCount);
1070 uint32_t textLength = 0;
1071 if (glyphsInCluster == fGlyphCount) {
1072 // consumes rest of glyphs and rest of text
1073 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1074 textLength = fTextByteLength - cluster;
1075 } else { // RTL text; last cluster.
1076 SkASSERT(fPreviousCluster < fTextByteLength);
1077 if (fPreviousCluster <= cluster) { // bad input.
1078 return Cluster{nullptr, 0, 0, 0};
1080 textLength = fPreviousCluster - cluster;
1083 return Cluster{fUtf8Text + cluster,
1088 SkASSERT(glyphsInCluster < fGlyphCount);
1089 uint32_t nextCluster = fClusters[glyphsInCluster];
1090 if (nextCluster >= fTextByteLength) {
1091 return Cluster{nullptr, 0, 0, 0}; // bad input.
1093 if (nextCluster > cluster) { // LTR text
1094 if (kInvalidCluster != fPreviousCluster) {
1095 return Cluster{nullptr, 0, 0, 0}; // bad input.
1097 textLength = nextCluster - cluster;
1098 } else { // RTL text
1099 SkASSERT(nextCluster < cluster);
1100 if (kInvalidCluster == fPreviousCluster) { // first cluster
1101 textLength = fTextByteLength - cluster;
1102 } else { // later cluster
1103 if (fPreviousCluster <= cluster) {
1104 return Cluster{nullptr, 0, 0, 0}; // bad input.
1106 textLength = fPreviousCluster - cluster;
1108 fPreviousCluster = cluster;
1110 uint32_t glyphIndex = fGlyphIndex;
1111 fGlyphCount -= glyphsInCluster;
1112 fGlyphIndex += glyphsInCluster;
1113 fClusters += glyphsInCluster;
1114 return Cluster{fUtf8Text + cluster,
1121 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1122 const uint32_t* fClusters;
1123 const char* fUtf8Text;
1124 uint32_t fGlyphCount;
1125 uint32_t fTextByteLength;
1126 uint32_t fGlyphIndex = 0;
1127 uint32_t fPreviousCluster = kInvalidCluster;
1128 bool fReversedChars = false;
1131 struct TextStorage {
1132 SkAutoTMalloc<char> fUtf8textStorage;
1133 SkAutoTMalloc<uint32_t> fClusterStorage;
1134 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1138 /** Given some unicode text (as passed to drawText(), convert to
1139 glyphs (via primitive shaping), while preserving
1140 glyph-to-character mapping information. */
1141 static Clusterator make_clusterator(
1142 const void* sourceText,
1143 size_t sourceByteCount,
1144 const SkPaint& paint,
1145 TextStorage* storage,
1147 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1148 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1149 SkASSERT(glyphCount > 0);
1150 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1151 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1152 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1153 uint32_t* clusters = storage->fClusterStorage.get();
1154 uint32_t utf8ByteCount = 0;
1155 const char* utf8Text = nullptr;
1156 switch (paint.getTextEncoding()) {
1157 case SkPaint::kUTF8_TextEncoding: {
1158 const char* txtPtr = (const char*)sourceText;
1159 for (int i = 0; i < glyphCount; ++i) {
1160 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1161 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1162 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1164 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1165 utf8ByteCount = SkToU32(sourceByteCount);
1166 utf8Text = (const char*)sourceText;
1169 case SkPaint::kUTF16_TextEncoding: {
1170 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1171 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1172 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1173 storage->fUtf8textStorage.reset(utf8ByteCount);
1174 char* txtPtr = storage->fUtf8textStorage.get();
1176 int clusterIndex = 0;
1177 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1178 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1179 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1180 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1182 SkASSERT(clusterIndex == glyphCount);
1183 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1184 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1187 case SkPaint::kUTF32_TextEncoding: {
1188 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1189 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1190 SkASSERT(glyphCount == utf32count);
1191 for (int i = 0; i < utf32count; ++i) {
1192 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1194 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1195 char* txtPtr = storage->fUtf8textStorage.get();
1197 for (int i = 0; i < utf32count; ++i) {
1198 clusters[i] = SkToU32(txtPtr - utf8Text);
1199 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1207 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1210 static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1211 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1214 static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1215 wStream->writeText("/");
1216 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1217 wStream->write(&prefix, 1);
1218 wStream->writeDecAsText(fontIndex);
1219 wStream->writeText(" ");
1220 SkPDFUtils::AppendScalar(textSize, wStream);
1221 wStream->writeText(" Tf\n");
1224 void SkPDFDevice::internalDrawText(
1225 const SkDraw& d, const void* sourceText, size_t sourceByteCount,
1226 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1227 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1228 uint32_t textByteLength, const char* utf8Text) {
1229 NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1230 if (srcPaint.getMaskFilter() != nullptr) {
1231 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1232 // making text unreadable (e.g. same text twice when using CSS shadows).
1235 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1236 if (srcPaint.isVerticalText()) {
1237 // Don't pretend we support drawing vertical text. It is not
1238 // clear to me how to switch to "vertical writing" mode in PDF.
1239 // Currently neither Chromium or Android set this flag.
1240 // https://bug.skia.org/5665
1243 if (0 == sourceByteCount || !sourceText) {
1246 SkPaint paint = calculate_text_paint(srcPaint);
1247 replace_srcmode_on_opaque_paint(&paint);
1248 if (!paint.getTypeface()) {
1249 paint.setTypeface(SkTypeface::MakeDefault());
1251 SkTypeface* typeface = paint.getTypeface();
1253 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1257 const SkAdvancedTypefaceMetrics* metrics =
1258 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1262 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1263 if (glyphCount <= 0) {
1267 // These three heap buffers are only used in the case where no glyphs
1268 // are passed to drawText() (most clients pass glyphs or a textblob).
1269 TextStorage storage;
1270 const SkGlyphID* glyphs = nullptr;
1271 Clusterator clusterator;
1272 if (textByteLength > 0) {
1273 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1274 glyphs = (const SkGlyphID*)sourceText;
1275 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1278 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1279 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1280 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1281 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1282 glyphs = (const SkGlyphID*)sourceText;
1283 clusterator = Clusterator(SkToU32(glyphCount));
1284 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1285 SkASSERT(nullptr == clusters);
1286 SkASSERT(nullptr == utf8Text);
1288 SkASSERT(nullptr == clusters);
1289 SkASSERT(nullptr == utf8Text);
1290 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1291 &storage, glyphCount);
1292 glyphs = storage.fGlyphStorage;
1294 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
1295 paint.setHinting(SkPaint::kNo_Hinting);
1296 SkAutoGlyphCache glyphCache(paint, nullptr, nullptr);
1298 SkPaint::Align alignment = paint.getTextAlign();
1299 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1300 SkPaint::kCenter_Align == alignment ? -0.5f :
1301 /* SkPaint::kRight_Align */ -1.0f;
1302 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
1303 SkScalar advance = 0;
1304 for (int i = 0; i < glyphCount; ++i) {
1305 advance += glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
1307 offset.offset(alignmentFactor * advance, 0);
1309 ScopedContentEntry content(this, d, paint, true);
1310 if (!content.entry()) {
1313 SkDynamicMemoryWStream* out = &content.entry()->fContent;
1314 SkScalar textSize = paint.getTextSize();
1315 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
1317 out->writeText("BT\n");
1318 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1320 const SkGlyphID maxGlyphID = metrics->fLastGlyphID;
1321 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1322 if (clusterator.reversedChars()) {
1323 out->writeText("/ReversedChars BMC\n");
1325 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1326 GlyphPositioner glyphPositioner(out,
1327 paint.getTextSkewX(),
1331 SkPDFFont* font = nullptr;
1333 while (Clusterator::Cluster c = clusterator.next()) {
1334 int index = c.fGlyphIndex;
1335 int glyphLimit = index + c.fGlyphCount;
1337 bool actualText = false;
1338 SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1339 if (c.fUtf8Text) { // real cluster
1340 // Check if `/ActualText` needed.
1341 const char* textPtr = c.fUtf8Text;
1342 // TODO(halcanary): validate utf8 input.
1343 SkUnichar unichar = SkUTF8_NextUnichar(&textPtr);
1344 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1345 if (textPtr < textEnd || // more characters left
1346 glyphLimit > index + 1 || // toUnicode wouldn't work
1347 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1349 glyphPositioner.flush();
1350 out->writeText("/Span<</ActualText <");
1351 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1352 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1353 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1354 while (textPtr < textEnd) {
1355 unichar = SkUTF8_NextUnichar(&textPtr);
1356 SkPDFUtils::WriteUTF16beHex(out, unichar);
1358 out->writeText("> >> BDC\n"); // begin marked-content sequence
1359 // with an associated property list.
1363 for (; index < glyphLimit; ++index) {
1364 SkGlyphID gid = glyphs[index];
1365 if (gid > maxGlyphID) {
1368 if (!font || !font->hasGlyph(gid)) {
1369 // Not yet specified font or need to switch font.
1370 int fontIndex = this->getFontResourceIndex(typeface, gid);
1371 // All preconditions for SkPDFFont::GetFontResource are met.
1372 SkASSERT(fontIndex >= 0);
1373 if (fontIndex < 0) {
1376 glyphPositioner.flush();
1377 update_font(out, fontIndex, textSize);
1378 font = fFontResources[fontIndex];
1379 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1383 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1386 SkScalar advance{0};
1387 if (!defaultPositioning) {
1388 advance = glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1389 xy = SkTextBlob::kFull_Positioning == positioning
1390 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1391 : SkPoint{pos[index], 0};
1392 if (alignment != SkPaint::kLeft_Align) {
1393 xy.offset(alignmentFactor * advance, 0);
1396 font->noteGlyphUsage(gid);
1397 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1398 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1403 void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1404 SkScalar x, SkScalar y, const SkPaint& paint) {
1405 this->internalDrawText(d, text, len, nullptr, SkTextBlob::kDefault_Positioning,
1406 SkPoint{x, y}, paint, nullptr, 0, nullptr);
1409 void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1410 const SkScalar pos[], int scalarsPerPos,
1411 const SkPoint& offset, const SkPaint& paint) {
1412 this->internalDrawText(d, text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
1413 offset, paint, nullptr, 0, nullptr);
1416 void SkPDFDevice::drawTextBlob(const SkDraw& draw, const SkTextBlob* blob, SkScalar x, SkScalar y,
1417 const SkPaint &paint, SkDrawFilter* drawFilter) {
1418 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1419 SkPaint runPaint(paint);
1420 it.applyFontToPaint(&runPaint);
1421 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1424 runPaint.setFlags(this->filterTextFlags(runPaint));
1425 SkPoint offset = it.offset() + SkPoint{x, y};
1426 this->internalDrawText(draw, it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
1427 it.pos(), it.positioning(), offset, runPaint,
1428 it.clusters(), it.textSize(), it.text());
1432 void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
1433 int vertexCount, const SkPoint verts[],
1434 const SkPoint texs[], const SkColor colors[],
1435 SkBlendMode, const uint16_t indices[],
1436 int indexCount, const SkPaint& paint) {
1437 if (d.fRC->isEmpty()) {
1440 // TODO: implement drawVertices
1443 void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1444 int x, int y, const SkPaint& paint) {
1445 SkASSERT(!paint.getImageFilter());
1447 // Check if the source device is really a bitmapdevice (because that's what we returned
1448 // from createDevice (likely due to an imagefilter)
1450 if (device->peekPixels(&pmap)) {
1452 bitmap.installPixels(pmap);
1453 this->drawSprite(d, bitmap, x, y, paint);
1457 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
1458 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
1460 SkScalar scalarX = SkIntToScalar(x);
1461 SkScalar scalarY = SkIntToScalar(y);
1462 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1463 SkRect r = l.rect.makeOffset(scalarX, scalarY);
1464 fLinkToURLs.emplace_back(r, l.data.get());
1466 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1467 SkRect r = l.rect.makeOffset(scalarX, scalarY);
1468 fLinkToDestinations.emplace_back(r, l.data.get());
1470 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1471 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
1472 fNamedDestinations.emplace_back(d.nameData.get(), p);
1475 if (pdfDevice->isContentEmpty()) {
1480 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1481 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
1482 if (!content.entry()) {
1485 if (content.needShape()) {
1487 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
1488 SkIntToScalar(device->width()),
1489 SkIntToScalar(device->height())));
1490 content.setShape(shape);
1492 if (!content.needSource()) {
1496 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
1497 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
1498 &content.entry()->fContent);
1501 sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1502 return SkSurface::MakeRaster(info, &props);
1506 sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
1507 SkTDArray<SkPDFObject*> fonts;
1508 fonts.setReserve(fFontResources.count());
1509 for (SkPDFFont* font : fFontResources) {
1512 return SkPDFResourceDict::Make(
1513 &fGraphicStateResources,
1519 sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
1520 auto mediaBox = sk_make_sp<SkPDFArray>();
1521 mediaBox->reserve(4);
1522 mediaBox->appendInt(0);
1523 mediaBox->appendInt(0);
1524 mediaBox->appendInt(fPageSize.width());
1525 mediaBox->appendInt(fPageSize.height());
1529 std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
1530 SkDynamicMemoryWStream buffer;
1531 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1532 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
1535 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, &buffer);
1536 for (const auto& entry : fContentEntries) {
1537 SkPoint translation;
1538 translation.iset(this->getOrigin());
1539 translation.negate();
1540 gsState.updateClip(entry.fState.fClipStack, entry.fState.fClipRegion,
1542 gsState.updateMatrix(entry.fState.fMatrix);
1543 gsState.updateDrawingState(entry.fState);
1545 entry.fContent.writeToStream(&buffer);
1547 gsState.drainStack();
1548 if (buffer.bytesWritten() > 0) {
1549 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1551 return skstd::make_unique<SkMemoryStream>();
1555 /* Draws an inverse filled path by using Path Ops to compute the positive
1556 * inverse using the current clip as the inverse bounds.
1557 * Return true if this was an inverse path and was properly handled,
1558 * otherwise returns false and the normal drawing routine should continue,
1559 * either as a (incorrect) fallback or because the path was not inverse
1560 * in the first place.
1562 bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
1563 const SkPaint& paint, bool pathIsMutable,
1564 const SkMatrix* prePathMatrix) {
1565 if (!origPath.isInverseFillType()) {
1569 if (d.fRC->isEmpty()) {
1573 SkPath modifiedPath;
1574 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1575 SkPaint noInversePaint(paint);
1577 // Merge stroking operations into final path.
1578 if (SkPaint::kStroke_Style == paint.getStyle() ||
1579 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1580 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1582 noInversePaint.setStyle(SkPaint::kFill_Style);
1583 noInversePaint.setStrokeWidth(0);
1584 pathPtr = &modifiedPath;
1586 // To be consistent with the raster output, hairline strokes
1587 // are rendered as non-inverted.
1588 modifiedPath.toggleInverseFillType();
1589 drawPath(d, modifiedPath, paint, nullptr, true);
1594 // Get bounds of clip in current transform space
1595 // (clip bounds are given in device space).
1597 SkMatrix transformInverse;
1598 SkMatrix totalMatrix = *d.fMatrix;
1599 if (prePathMatrix) {
1600 totalMatrix.preConcat(*prePathMatrix);
1602 if (!totalMatrix.invert(&transformInverse)) {
1605 bounds.set(d.fRC->getBounds());
1606 transformInverse.mapRect(&bounds);
1608 // Extend the bounds by the line width (plus some padding)
1609 // so the edge doesn't cause a visible stroke.
1610 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1611 paint.getStrokeWidth() + SK_Scalar1);
1613 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1617 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
1621 void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
1622 const SkMatrix& matrix,
1623 const char key[], SkData* value) {
1628 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1629 SkPoint transformedPoint;
1630 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1631 fNamedDestinations.emplace_back(value, transformedPoint);
1635 void SkPDFDevice::handlePathAnnotation(const SkPath& path,
1637 const char key[], SkData* value) {
1642 SkRasterClip clip = *d.fRC;
1643 clip.op(path, *d.fMatrix, SkIRect::MakeWH(width(), height()),
1644 SkRegion::kIntersect_Op,
1646 SkRect transformedRect = SkRect::Make(clip.getBounds());
1648 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
1649 if (!transformedRect.isEmpty()) {
1650 fLinkToURLs.emplace_back(transformedRect, value);
1652 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
1653 if (!transformedRect.isEmpty()) {
1654 fLinkToDestinations.emplace_back(transformedRect, value);
1659 void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1660 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
1661 for (const RectWithData& rectWithURL : fLinkToURLs) {
1663 fInitialTransform.mapRect(&r, rectWithURL.rect);
1664 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
1666 for (const RectWithData& linkToDestination : fLinkToDestinations) {
1668 fInitialTransform.mapRect(&r, linkToDestination.rect);
1669 array->appendObject(
1670 create_link_named_dest(linkToDestination.data.get(), r));
1674 void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
1675 for (const NamedDestination& dest : fNamedDestinations) {
1676 auto pdfDest = sk_make_sp<SkPDFArray>();
1677 pdfDest->reserve(5);
1678 pdfDest->appendObjRef(sk_ref_sp(page));
1679 pdfDest->appendName("XYZ");
1680 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
1681 pdfDest->appendScalar(p.x());
1682 pdfDest->appendScalar(p.y());
1683 pdfDest->appendInt(0); // Leave zoom unchanged
1684 SkString name(static_cast<const char*>(dest.nameData->data()));
1685 dict->insertObject(name, std::move(pdfDest));
1689 sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
1690 SkMatrix inverseTransform = SkMatrix::I();
1691 if (!fInitialTransform.isIdentity()) {
1692 if (!fInitialTransform.invert(&inverseTransform)) {
1693 SkDEBUGFAIL("Layer initial transform should be invertible.");
1694 inverseTransform.reset();
1697 sk_sp<SkPDFObject> xobject =
1698 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
1699 this->makeResourceDict(), inverseTransform, nullptr);
1700 // We always draw the form xobjects that we create back into the device, so
1701 // we simply preserve the font usage instead of pulling it out and merging
1702 // it back in later.
1703 this->cleanUp(); // Reset this device to have no content.
1708 void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1709 sk_sp<SkPDFObject> mask,
1710 const SkClipStack* clipStack,
1711 const SkRegion& clipRegion,
1714 if (clipRegion.isEmpty() && !invertClip) {
1718 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
1719 std::move(mask), invertClip,
1720 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
1725 paint.setBlendMode(mode);
1726 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
1727 if (!content.entry()) {
1730 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1731 &content.entry()->fContent);
1732 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
1734 // Call makeNoSmaskGraphicState() instead of
1735 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1737 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
1738 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
1739 &content.entry()->fContent);
1742 SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1743 const SkRegion& clipRegion,
1744 const SkMatrix& matrix,
1745 const SkPaint& paint,
1747 sk_sp<SkPDFObject>* dst) {
1749 if (clipRegion.isEmpty()) {
1753 // The clip stack can come from an SkDraw where it is technically optional.
1754 SkClipStack synthesizedClipStack;
1755 if (clipStack == nullptr) {
1756 if (clipRegion == fExistingClipRegion) {
1757 clipStack = &fExistingClipStack;
1759 // GraphicStackState::updateClip expects the clip stack to have
1760 // fExistingClip as a prefix, so start there, then set the clip
1761 // to the passed region.
1762 synthesizedClipStack = fExistingClipStack;
1764 clipRegion.getBoundaryPath(&clipPath);
1765 synthesizedClipStack.clipPath(clipPath, SkMatrix::I(), kReplace_SkClipOp, false);
1766 clipStack = &synthesizedClipStack;
1770 SkBlendMode blendMode = paint.getBlendMode();
1772 // For the following modes, we want to handle source and destination
1773 // separately, so make an object of what's already there.
1774 if (blendMode == SkBlendMode::kClear ||
1775 blendMode == SkBlendMode::kSrc ||
1776 blendMode == SkBlendMode::kSrcIn ||
1777 blendMode == SkBlendMode::kDstIn ||
1778 blendMode == SkBlendMode::kSrcOut ||
1779 blendMode == SkBlendMode::kDstOut ||
1780 blendMode == SkBlendMode::kSrcATop ||
1781 blendMode == SkBlendMode::kDstATop ||
1782 blendMode == SkBlendMode::kModulate) {
1783 if (!isContentEmpty()) {
1784 *dst = this->makeFormXObjectFromDevice();
1785 SkASSERT(isContentEmpty());
1786 } else if (blendMode != SkBlendMode::kSrc &&
1787 blendMode != SkBlendMode::kSrcOut) {
1788 // Except for Src and SrcOut, if there isn't anything already there,
1793 // TODO(vandebo): Figure out how/if we can handle the following modes:
1796 // Dst xfer mode doesn't draw source at all.
1797 if (blendMode == SkBlendMode::kDst) {
1801 SkPDFDevice::ContentEntry* entry;
1802 if (fContentEntries.back() && fContentEntries.back()->fContent.getOffset() == 0) {
1803 entry = fContentEntries.back();
1804 } else if (blendMode != SkBlendMode::kDstOver) {
1805 entry = fContentEntries.emplace_back();
1807 entry = fContentEntries.emplace_front();
1809 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
1810 hasText, &entry->fState);
1814 void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
1815 sk_sp<SkPDFObject> dst,
1817 if (blendMode != SkBlendMode::kClear &&
1818 blendMode != SkBlendMode::kSrc &&
1819 blendMode != SkBlendMode::kDstOver &&
1820 blendMode != SkBlendMode::kSrcIn &&
1821 blendMode != SkBlendMode::kDstIn &&
1822 blendMode != SkBlendMode::kSrcOut &&
1823 blendMode != SkBlendMode::kDstOut &&
1824 blendMode != SkBlendMode::kSrcATop &&
1825 blendMode != SkBlendMode::kDstATop &&
1826 blendMode != SkBlendMode::kModulate) {
1830 if (blendMode == SkBlendMode::kDstOver) {
1832 if (fContentEntries.front()->fContent.getOffset() == 0) {
1833 // For DstOver, an empty content entry was inserted before the rest
1834 // of the content entries. If nothing was drawn, it needs to be
1836 fContentEntries.pop_front();
1841 SkASSERT(blendMode == SkBlendMode::kSrc ||
1842 blendMode == SkBlendMode::kSrcOut);
1847 SkASSERT(fContentEntries.count() == 1);
1848 // Changing the current content into a form-xobject will destroy the clip
1849 // objects which is fine since the xobject will already be clipped. However
1850 // if source has shape, we need to clip it too, so a copy of the clip is
1853 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
1854 SkRegion clipRegion = fContentEntries.front()->fState.fClipRegion;
1860 sk_sp<SkPDFObject> srcFormXObject;
1861 if (isContentEmpty()) {
1862 // If nothing was drawn and there's no shape, then the draw was a
1863 // no-op, but dst needs to be restored for that to be true.
1864 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1865 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1867 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1868 blendMode == SkBlendMode::kSrcATop) {
1869 ScopedContentEntry content(this, &fExistingClipStack,
1870 fExistingClipRegion, identity,
1872 // TODO: addXObjectResource take sk_sp
1873 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
1874 &content.entry()->fContent);
1877 blendMode = SkBlendMode::kClear;
1880 SkASSERT(fContentEntries.count() == 1);
1881 srcFormXObject = this->makeFormXObjectFromDevice();
1884 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1886 if (blendMode == SkBlendMode::kSrcATop) {
1887 // TODO(vandebo): In order to properly support SrcATop we have to track
1888 // the shape of what's been drawn at all times. It's the intersection of
1889 // the non-transparent parts of the device and the outlines (shape) of
1890 // all images and devices drawn.
1891 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
1892 &fExistingClipStack, fExistingClipRegion,
1893 SkBlendMode::kSrcOver, true);
1895 if (shape != nullptr) {
1896 // Draw shape into a form-xobject.
1897 SkRasterClip rc(clipRegion);
1899 d.fMatrix = &identity;
1901 d.fClipStack = &clipStack;
1902 SkPaint filledPaint;
1903 filledPaint.setColor(SK_ColorBLACK);
1904 filledPaint.setStyle(SkPaint::kFill_Style);
1905 this->drawPath(d, *shape, filledPaint, nullptr, true);
1906 drawFormXObjectWithMask(addXObjectResource(dst.get()),
1907 this->makeFormXObjectFromDevice(),
1908 &fExistingClipStack, fExistingClipRegion,
1909 SkBlendMode::kSrcOver, true);
1912 drawFormXObjectWithMask(addXObjectResource(dst.get()), srcFormXObject,
1913 &fExistingClipStack, fExistingClipRegion,
1914 SkBlendMode::kSrcOver, true);
1918 if (blendMode == SkBlendMode::kClear) {
1920 } else if (blendMode == SkBlendMode::kSrc ||
1921 blendMode == SkBlendMode::kDstATop) {
1922 ScopedContentEntry content(this, &fExistingClipStack,
1923 fExistingClipRegion, identity, stockPaint);
1924 if (content.entry()) {
1925 SkPDFUtils::DrawFormXObject(
1926 this->addXObjectResource(srcFormXObject.get()),
1927 &content.entry()->fContent);
1929 if (blendMode == SkBlendMode::kSrc) {
1932 } else if (blendMode == SkBlendMode::kSrcATop) {
1933 ScopedContentEntry content(this, &fExistingClipStack,
1934 fExistingClipRegion, identity, stockPaint);
1935 if (content.entry()) {
1936 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
1937 &content.entry()->fContent);
1941 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1942 blendMode == SkBlendMode::kDstIn ||
1943 blendMode == SkBlendMode::kSrcOut ||
1944 blendMode == SkBlendMode::kDstOut ||
1945 blendMode == SkBlendMode::kSrcATop ||
1946 blendMode == SkBlendMode::kDstATop ||
1947 blendMode == SkBlendMode::kModulate);
1949 if (blendMode == SkBlendMode::kSrcIn ||
1950 blendMode == SkBlendMode::kSrcOut ||
1951 blendMode == SkBlendMode::kSrcATop) {
1952 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1954 &fExistingClipStack, fExistingClipRegion,
1955 SkBlendMode::kSrcOver,
1956 blendMode == SkBlendMode::kSrcOut);
1959 SkBlendMode mode = SkBlendMode::kSrcOver;
1960 int resourceID = addXObjectResource(dst.get());
1961 if (blendMode == SkBlendMode::kModulate) {
1962 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1963 std::move(dst), &fExistingClipStack,
1964 fExistingClipRegion,
1965 SkBlendMode::kSrcOver, false);
1966 mode = SkBlendMode::kMultiply;
1968 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
1969 &fExistingClipStack, fExistingClipRegion, mode,
1970 blendMode == SkBlendMode::kDstOut);
1975 bool SkPDFDevice::isContentEmpty() {
1976 if (!fContentEntries.front() || fContentEntries.front()->fContent.getOffset() == 0) {
1977 SkASSERT(fContentEntries.count() <= 1);
1983 void SkPDFDevice::populateGraphicStateEntryFromPaint(
1984 const SkMatrix& matrix,
1985 const SkClipStack& clipStack,
1986 const SkRegion& clipRegion,
1987 const SkPaint& paint,
1989 SkPDFDevice::GraphicStateEntry* entry) {
1990 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1991 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1992 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
1994 entry->fMatrix = matrix;
1995 entry->fClipStack = clipStack;
1996 entry->fClipRegion = clipRegion;
1997 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1998 entry->fShaderIndex = -1;
2000 // PDF treats a shader as a color, so we only set one or the other.
2001 sk_sp<SkPDFObject> pdfShader;
2002 SkShader* shader = paint.getShader();
2003 SkColor color = paint.getColor();
2005 // PDF positions patterns relative to the initial transform, so
2006 // we need to apply the current transform to the shader parameters.
2007 SkMatrix transform = matrix;
2008 transform.postConcat(fInitialTransform);
2010 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2011 // a pattern the size of the current clip.
2012 SkIRect bounds = clipRegion.getBounds();
2014 // We need to apply the initial transform to bounds in order to get
2015 // bounds in a consistent coordinate system.
2017 boundsTemp.set(bounds);
2018 fInitialTransform.mapRect(&boundsTemp);
2019 boundsTemp.roundOut(&bounds);
2021 SkScalar rasterScale =
2022 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2023 pdfShader = SkPDFShader::GetPDFShader(
2024 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
2026 if (pdfShader.get()) {
2027 // pdfShader has been canonicalized so we can directly compare
2029 int resourceIndex = fShaderResources.find(pdfShader.get());
2030 if (resourceIndex < 0) {
2031 resourceIndex = fShaderResources.count();
2032 fShaderResources.push(pdfShader.get());
2033 pdfShader.get()->ref();
2035 entry->fShaderIndex = resourceIndex;
2037 // A color shader is treated as an invalid shader so we don't have
2038 // to set a shader just for a color.
2039 SkShader::GradientInfo gradientInfo;
2040 SkColor gradientColor;
2041 gradientInfo.fColors = &gradientColor;
2042 gradientInfo.fColorOffsets = nullptr;
2043 gradientInfo.fColorCount = 1;
2044 if (shader->asAGradient(&gradientInfo) ==
2045 SkShader::kColor_GradientType) {
2046 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2047 color = gradientColor;
2052 sk_sp<SkPDFGraphicState> newGraphicState;
2053 if (color == paint.getColor()) {
2054 newGraphicState.reset(
2055 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
2057 SkPaint newPaint = paint;
2058 newPaint.setColor(color);
2059 newGraphicState.reset(
2060 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
2062 int resourceIndex = addGraphicStateResource(newGraphicState.get());
2063 entry->fGraphicStateIndex = resourceIndex;
2066 entry->fTextScaleX = paint.getTextScaleX();
2067 entry->fTextFill = paint.getStyle();
2069 entry->fTextScaleX = 0;
2073 int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
2074 // Assumes that gs has been canonicalized (so we can directly compare
2076 int result = fGraphicStateResources.find(gs);
2078 result = fGraphicStateResources.count();
2079 fGraphicStateResources.push(gs);
2085 int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2086 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
2087 // Assumes that xobject has been canonicalized (so we can directly compare
2089 int result = fXObjectResources.find(xObject);
2091 result = fXObjectResources.count();
2092 fXObjectResources.push(SkRef(xObject));
2097 int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
2098 sk_sp<SkPDFFont> newFont(
2099 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
2103 int resourceIndex = fFontResources.find(newFont.get());
2104 if (resourceIndex < 0) {
2105 fDocument->registerFont(newFont.get());
2106 resourceIndex = fFontResources.count();
2107 fFontResources.push(newFont.release());
2109 return resourceIndex;
2112 static SkSize rect_to_size(const SkRect& r) {
2113 return SkSize::Make(r.width(), r.height());
2116 static sk_sp<SkImage> color_filter(const SkImageSubset& imageSubset,
2117 SkColorFilter* colorFilter) {
2119 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.dimensions()));
2121 SkCanvas* canvas = surface->getCanvas();
2122 canvas->clear(SK_ColorTRANSPARENT);
2124 paint.setColorFilter(sk_ref_sp(colorFilter));
2125 imageSubset.draw(canvas, &paint);
2127 return surface->makeImageSnapshot();
2130 ////////////////////////////////////////////////////////////////////////////////
2131 void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2132 const SkClipStack* clipStack,
2133 const SkRegion& origClipRegion,
2134 SkImageSubset imageSubset,
2135 const SkPaint& paint) {
2136 if (imageSubset.dimensions().isZero()) {
2139 #ifdef SK_PDF_IMAGE_STATS
2140 gDrawImageCalls.fetch_add(1);
2142 SkMatrix matrix = origMatrix;
2143 SkRegion perspectiveBounds;
2144 const SkRegion* clipRegion = &origClipRegion;
2146 // Rasterize the bitmap using perspective in a new bitmap.
2147 if (origMatrix.hasPerspective()) {
2148 if (fRasterDpi == 0) {
2151 // Transform the bitmap in the new space, without taking into
2152 // account the initial transform.
2153 SkPath perspectiveOutline;
2154 SkRect imageBounds = SkRect::Make(imageSubset.bounds());
2155 perspectiveOutline.addRect(imageBounds);
2156 perspectiveOutline.transform(origMatrix);
2158 // TODO(edisonn): perf - use current clip too.
2159 // Retrieve the bounds of the new shape.
2160 SkRect bounds = perspectiveOutline.getBounds();
2162 // Transform the bitmap in the new space, taking into
2163 // account the initial transform.
2164 SkMatrix total = origMatrix;
2165 total.postConcat(fInitialTransform);
2166 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2167 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2168 total.postScale(dpiScale, dpiScale);
2170 SkPath physicalPerspectiveOutline;
2171 physicalPerspectiveOutline.addRect(imageBounds);
2172 physicalPerspectiveOutline.transform(total);
2174 SkRect physicalPerspectiveBounds =
2175 physicalPerspectiveOutline.getBounds();
2176 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2177 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
2179 // TODO(edisonn): A better approach would be to use a bitmap shader
2180 // (in clamp mode) and draw a rect over the entire bounding box. Then
2181 // intersect perspectiveOutline to the clip. That will avoid introducing
2182 // alpha to the image while still giving good behavior at the edge of
2183 // the image. Avoiding alpha will reduce the pdf size and generation
2186 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2188 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
2192 SkCanvas* canvas = surface->getCanvas();
2193 canvas->clear(SK_ColorTRANSPARENT);
2195 SkScalar deltaX = bounds.left();
2196 SkScalar deltaY = bounds.top();
2198 SkMatrix offsetMatrix = origMatrix;
2199 offsetMatrix.postTranslate(-deltaX, -deltaY);
2200 offsetMatrix.postScale(scaleX, scaleY);
2202 // Translate the draw in the new canvas, so we perfectly fit the
2203 // shape in the bitmap.
2204 canvas->setMatrix(offsetMatrix);
2205 imageSubset.draw(canvas, nullptr);
2206 // Make sure the final bits are in the bitmap.
2209 // In the new space, we use the identity matrix translated
2210 // and scaled to reflect DPI.
2211 matrix.setScale(1 / scaleX, 1 / scaleY);
2212 matrix.postTranslate(deltaX, deltaY);
2214 perspectiveBounds.setRect(bounds.roundOut());
2215 clipRegion = &perspectiveBounds;
2217 imageSubset = SkImageSubset(surface->makeImageSnapshot());
2221 // Adjust for origin flip.
2222 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2223 scaled.postTranslate(0, SK_Scalar1);
2224 // Scale the image up from 1x1 to WxH.
2225 SkIRect subset = imageSubset.bounds();
2226 scaled.postScale(SkIntToScalar(imageSubset.dimensions().width()),
2227 SkIntToScalar(imageSubset.dimensions().height()));
2228 scaled.postConcat(matrix);
2229 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
2230 if (!content.entry()) {
2233 if (content.needShape()) {
2235 shape.addRect(SkRect::Make(subset));
2236 shape.transform(matrix);
2237 content.setShape(shape);
2239 if (!content.needSource()) {
2243 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
2244 // TODO(https://bug.skia.org/4378): implement colorfilter on other
2245 // draw calls. This code here works for all
2246 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2247 // rasterize a layer on this backend). Fortuanely, this seems
2248 // to be how Chromium impements most color-filters.
2249 sk_sp<SkImage> img = color_filter(imageSubset, colorFilter);
2250 imageSubset = SkImageSubset(std::move(img));
2251 // TODO(halcanary): de-dupe this by caching filtered images.
2252 // (maybe in the resource cache?)
2255 SkBitmapKey key = imageSubset.getKey();
2256 sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
2258 sk_sp<SkImage> img = imageSubset.makeImage();
2262 pdfimage = SkPDFCreateBitmapObject(
2263 std::move(img), fDocument->canon()->getPixelSerializer());
2267 fDocument->serialize(pdfimage); // serialize images early.
2268 fDocument->canon()->addPDFBitmap(key, pdfimage);
2270 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
2271 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
2272 &content.entry()->fContent);
2275 ///////////////////////////////////////////////////////////////////////////////////////////////////
2277 #include "SkSpecialImage.h"
2278 #include "SkImageFilter.h"
2280 void SkPDFDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
2281 const SkPaint& paint) {
2282 SkASSERT(!srcImg->isTextureBacked());
2286 SkImageFilter* filter = paint.getImageFilter();
2288 SkIPoint offset = SkIPoint::Make(0, 0);
2289 SkMatrix matrix = *draw.fMatrix;
2290 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
2291 const SkIRect clipBounds = draw.fRC->getBounds().makeOffset(-x, -y);
2292 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
2293 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2294 // in the same color space as the source (this is different from all other backends).
2295 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2296 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
2298 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2300 SkPaint tmpUnfiltered(paint);
2301 tmpUnfiltered.setImageFilter(nullptr);
2302 if (resultImg->getROPixels(&resultBM)) {
2303 this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2307 if (srcImg->getROPixels(&resultBM)) {
2308 this->drawSprite(draw, resultBM, x, y, paint);
2313 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2314 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2317 sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
2318 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2319 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2320 // a color space, so we always decode in legacy mode for now.
2321 SkColorSpace* legacyColorSpace = nullptr;
2322 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
2323 image->makeNonTextureImage(), legacyColorSpace);
2326 sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
2330 SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2331 // We always return a transient cache, so it is freed after each
2332 // filter traversal.
2333 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);