blob: 0e54bfd76503f5308c7455df34fe635d77494d1a [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
halcanarye06ca962016-09-09 05:34:55 -07009
halcanaryf59d18a2016-09-16 14:44:57 -070010#include "SkAdvancedTypefaceMetrics.h"
reedf70b5312016-03-04 16:36:20 -080011#include "SkAnnotationKeys.h"
reed7503d602016-07-15 14:23:29 -070012#include "SkBitmapDevice.h"
martina.kollarovab8d6af12016-06-29 05:12:31 -070013#include "SkBitmapKey.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000014#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070015#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000016#include "SkDraw.h"
halcanarye06ca962016-09-09 05:34:55 -070017#include "SkDrawFilter.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000018#include "SkGlyphCache.h"
halcanary022c2bd2016-09-02 11:29:46 -070019#include "SkMakeUnique.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000020#include "SkPath.h"
reeda4393342016-03-18 11:22:57 -070021#include "SkPathEffect.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000022#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070023#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070024#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070025#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000026#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000027#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000028#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000029#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000030#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000031#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000032#include "SkPDFUtils.h"
wangxianzhuef6c50a2015-09-17 20:38:02 -070033#include "SkRasterClip.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000034#include "SkRRect.h"
halcanary4871f222016-08-26 13:17:44 -070035#include "SkScopeExit.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000036#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070037#include "SkSurface.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000038#include "SkTemplates.h"
halcanarye06ca962016-09-09 05:34:55 -070039#include "SkTextBlobRunIterator.h"
40#include "SkTextFormatParams.h"
halcanaryf59d18a2016-09-16 14:44:57 -070041#include "SkUtils.h"
halcanarya6814332015-05-27 08:53:36 -070042#include "SkXfermodeInterpretation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000043
edisonn@google.com73a7ea32013-11-11 20:55:15 +000044#define DPI_FOR_RASTER_SCALE_ONE 72
45
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000046// Utility functions
47
halcanarya6814332015-05-27 08:53:36 -070048// If the paint will definitely draw opaquely, replace kSrc_Mode with
49// kSrcOver_Mode. http://crbug.com/473572
50static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
51 if (kSrcOver_SkXfermodeInterpretation
52 == SkInterpretXfermode(*paint, false)) {
halcanary96fcdcc2015-08-27 07:41:13 -070053 paint->setXfermode(nullptr);
halcanarya6814332015-05-27 08:53:36 -070054 }
55}
56
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000057static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000058 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -070059 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000060 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070061 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000062 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070063 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000064 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000065}
66
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000067static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000068 SkPaint result = paint;
69 if (result.isFakeBoldText()) {
70 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
71 kStdFakeBoldInterpKeys,
72 kStdFakeBoldInterpValues,
73 kStdFakeBoldInterpLength);
74 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000075 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000076 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000077 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000078 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000079 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080 result.setStrokeWidth(width);
81 }
82 return result;
83}
84
halcanary2be7e012016-03-28 11:58:08 -070085SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
86 : fColor(SK_ColorBLACK)
87 , fTextScaleX(SK_Scalar1)
88 , fTextFill(SkPaint::kFill_Style)
89 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -070090 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000091 fMatrix.reset();
92}
93
halcanary2be7e012016-03-28 11:58:08 -070094bool SkPDFDevice::GraphicStateEntry::compareInitialState(
95 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +000096 return fColor == cur.fColor &&
97 fShaderIndex == cur.fShaderIndex &&
98 fGraphicStateIndex == cur.fGraphicStateIndex &&
99 fMatrix == cur.fMatrix &&
100 fClipStack == cur.fClipStack &&
101 (fTextScaleX == 0 ||
102 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000103}
104
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000105class GraphicStackState {
106public:
107 GraphicStackState(const SkClipStack& existingClipStack,
108 const SkRegion& existingClipRegion,
109 SkWStream* contentStream)
110 : fStackDepth(0),
111 fContentStream(contentStream) {
112 fEntries[0].fClipStack = existingClipStack;
113 fEntries[0].fClipRegion = existingClipRegion;
114 }
115
116 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000117 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000118 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700119 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000120
121 void drainStack();
122
123private:
124 void push();
125 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700126 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000127
128 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
129 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700130 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000131 int fStackDepth;
132 SkWStream* fContentStream;
133};
134
135void GraphicStackState::drainStack() {
136 while (fStackDepth) {
137 pop();
138 }
139}
140
141void GraphicStackState::push() {
142 SkASSERT(fStackDepth < kMaxStackDepth);
143 fContentStream->writeText("q\n");
144 fStackDepth++;
145 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
146}
147
148void GraphicStackState::pop() {
149 SkASSERT(fStackDepth > 0);
150 fContentStream->writeText("Q\n");
151 fStackDepth--;
152}
153
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000154/* Calculate an inverted path's equivalent non-inverted path, given the
155 * canvas bounds.
156 * outPath may alias with invPath (since this is supported by PathOps).
157 */
158static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
159 SkPath* outPath) {
160 SkASSERT(invPath.isInverseFillType());
161
162 SkPath clipPath;
163 clipPath.addRect(bounds);
164
reedcdb42bb2015-06-26 10:23:07 -0700165 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000166}
167
168// Sanity check the numerical values of the SkRegion ops and PathOps ops
169// enums so region_op_to_pathops_op can do a straight passthrough cast.
170// If these are failing, it may be necessary to make region_op_to_pathops_op
171// do more.
bungeman99fe8222015-08-20 07:57:51 -0700172static_assert(SkRegion::kDifference_Op == (int)kDifference_SkPathOp, "region_pathop_mismatch");
173static_assert(SkRegion::kIntersect_Op == (int)kIntersect_SkPathOp, "region_pathop_mismatch");
174static_assert(SkRegion::kUnion_Op == (int)kUnion_SkPathOp, "region_pathop_mismatch");
175static_assert(SkRegion::kXOR_Op == (int)kXOR_SkPathOp, "region_pathop_mismatch");
176static_assert(SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkPathOp,
177 "region_pathop_mismatch");
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000178
179static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
180 SkASSERT(op >= 0);
181 SkASSERT(op <= SkRegion::kReverseDifference_Op);
182 return (SkPathOp)op;
183}
184
185/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
186 * Returns true if successful, or false if not successful.
187 * If successful, the resulting clip is stored in outClipPath.
188 * If not successful, outClipPath is undefined, and a fallback method
189 * should be used.
190 */
191static bool get_clip_stack_path(const SkMatrix& transform,
192 const SkClipStack& clipStack,
193 const SkRegion& clipRegion,
194 SkPath* outClipPath) {
195 outClipPath->reset();
196 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
197
198 const SkClipStack::Element* clipEntry;
199 SkClipStack::Iter iter;
200 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
201 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
202 SkPath entryPath;
203 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
204 outClipPath->reset();
205 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
206 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000207 } else {
208 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000209 }
210 entryPath.transform(transform);
211
212 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
213 *outClipPath = entryPath;
214 } else {
215 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
216 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
217 return false;
218 }
219 }
220 }
221
222 if (outClipPath->isInverseFillType()) {
223 // The bounds are slightly outset to ensure this is correct in the
224 // face of floating-point accuracy and possible SkRegion bitmap
225 // approximations.
226 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
227 clipBounds.outset(SK_Scalar1, SK_Scalar1);
228 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
229 return false;
230 }
231 }
232 return true;
233}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000234
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000235// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000236// graphic state stack, and the fact that we can know all the clips used
237// on the page to optimize this.
238void GraphicStackState::updateClip(const SkClipStack& clipStack,
239 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000240 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000241 if (clipStack == currentEntry()->fClipStack) {
242 return;
243 }
244
245 while (fStackDepth > 0) {
246 pop();
247 if (clipStack == currentEntry()->fClipStack) {
248 return;
249 }
250 }
251 push();
252
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000253 currentEntry()->fClipStack = clipStack;
254 currentEntry()->fClipRegion = clipRegion;
255
256 SkMatrix transform;
257 transform.setTranslate(translation.fX, translation.fY);
258
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000259 SkPath clipPath;
260 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700261 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
262 SkPath::FillType clipFill = clipPath.getFillType();
263 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
264 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
265 if (clipFill == SkPath::kEvenOdd_FillType) {
266 fContentStream->writeText("W* n\n");
267 } else {
268 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000269 }
270 }
halcanary5edf2902016-09-07 09:05:25 -0700271 // If Op() fails (pathological case; e.g. input values are
272 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000273}
274
275void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
276 if (matrix == currentEntry()->fMatrix) {
277 return;
278 }
279
280 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
281 SkASSERT(fStackDepth > 0);
282 SkASSERT(fEntries[fStackDepth].fClipStack ==
283 fEntries[fStackDepth -1].fClipStack);
284 pop();
285
286 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
287 }
288 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
289 return;
290 }
291
292 push();
293 SkPDFUtils::AppendTransform(matrix, fContentStream);
294 currentEntry()->fMatrix = matrix;
295}
296
halcanary2be7e012016-03-28 11:58:08 -0700297void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000298 // PDF treats a shader as a color, so we only set one or the other.
299 if (state.fShaderIndex >= 0) {
300 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000301 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000302 currentEntry()->fShaderIndex = state.fShaderIndex;
303 }
304 } else {
305 if (state.fColor != currentEntry()->fColor ||
306 currentEntry()->fShaderIndex >= 0) {
307 emit_pdf_color(state.fColor, fContentStream);
308 fContentStream->writeText("RG ");
309 emit_pdf_color(state.fColor, fContentStream);
310 fContentStream->writeText("rg\n");
311 currentEntry()->fColor = state.fColor;
312 currentEntry()->fShaderIndex = -1;
313 }
314 }
315
316 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000317 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000318 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
319 }
320
321 if (state.fTextScaleX) {
322 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
323 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
324 SkIntToScalar(100));
halcanarybc4696b2015-05-06 10:56:04 -0700325 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000326 fContentStream->writeText(" Tz\n");
327 currentEntry()->fTextScaleX = state.fTextScaleX;
328 }
329 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700330 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
331 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
332 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000333 fContentStream->writeDecAsText(state.fTextFill);
334 fContentStream->writeText(" Tr\n");
335 currentEntry()->fTextFill = state.fTextFill;
336 }
337 }
338}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000339
reed76033be2015-03-14 10:54:31 -0700340static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700341 // PDF does not support image filters, so render them on CPU.
342 // Note that this rendering is done at "screen" resolution (100dpi), not
343 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700344 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800345 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700346
347 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700348 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700349}
350
351SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700352 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700353 // need to return a raster device, which we will detect in drawDevice()
354 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700355 }
fmalita6987dca2014-11-13 08:33:37 -0800356 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanary989da4a2016-03-21 14:33:17 -0700357 return SkPDFDevice::Create(size, fRasterDpi, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000358}
359
halcanary989da4a2016-03-21 14:33:17 -0700360SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
361
bsalomon@google.come97f0852011-06-17 13:10:25 +0000362
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000363
364// A helper class to automatically finish a ContentEntry at the end of a
365// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000366class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000367public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000368 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
369 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000370 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700371 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000372 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700373 fDstFormXObject(nullptr) {
reed1e7f5e72016-04-27 07:49:17 -0700374 init(draw.fClipStack, draw.fRC->bwRgn(), *draw.fMatrix, paint, hasText);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000375 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000376 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
377 const SkRegion& clipRegion, const SkMatrix& matrix,
378 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000379 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700380 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000381 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700382 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000383 init(clipStack, clipRegion, matrix, paint, hasText);
384 }
385
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000386 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000387 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000388 SkPath* shape = &fShape;
389 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700390 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000391 }
halcanarydabd4f02016-08-03 11:16:56 -0700392 fDevice->finishContentEntry(fXfermode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000393 }
394 }
395
halcanary2be7e012016-03-28 11:58:08 -0700396 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000397
398 /* Returns true when we explicitly need the shape of the drawing. */
399 bool needShape() {
400 switch (fXfermode) {
401 case SkXfermode::kClear_Mode:
402 case SkXfermode::kSrc_Mode:
403 case SkXfermode::kSrcIn_Mode:
404 case SkXfermode::kSrcOut_Mode:
405 case SkXfermode::kDstIn_Mode:
406 case SkXfermode::kDstOut_Mode:
407 case SkXfermode::kSrcATop_Mode:
408 case SkXfermode::kDstATop_Mode:
409 case SkXfermode::kModulate_Mode:
410 return true;
411 default:
412 return false;
413 }
414 }
415
416 /* Returns true unless we only need the shape of the drawing. */
417 bool needSource() {
418 if (fXfermode == SkXfermode::kClear_Mode) {
419 return false;
420 }
421 return true;
422 }
423
424 /* If the shape is different than the alpha component of the content, then
425 * setShape should be called with the shape. In particular, images and
426 * devices have rectangular shape.
427 */
428 void setShape(const SkPath& shape) {
429 fShape = shape;
430 }
431
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000432private:
433 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700434 SkPDFDevice::ContentEntry* fContentEntry;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000435 SkXfermode::Mode fXfermode;
halcanarydabd4f02016-08-03 11:16:56 -0700436 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000437 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000438
439 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
440 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000441 // Shape has to be flatten before we get here.
442 if (matrix.hasPerspective()) {
443 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000444 return;
445 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000446 if (paint.getXfermode()) {
447 paint.getXfermode()->asMode(&fXfermode);
448 }
449 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
450 matrix, paint, hasText,
451 &fDstFormXObject);
452 }
453};
454
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000455////////////////////////////////////////////////////////////////////////////////
456
halcanary989da4a2016-03-21 14:33:17 -0700457SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
reed589a39e2016-08-20 07:59:19 -0700458 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
459 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700460 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800461 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
halcanarya1f1ee92015-02-20 06:17:26 -0800462 , fRasterDpi(rasterDpi)
halcanary989da4a2016-03-21 14:33:17 -0700463 , fDocument(doc) {
halcanarya1f1ee92015-02-20 06:17:26 -0800464 SkASSERT(pageSize.width() > 0);
465 SkASSERT(pageSize.height() > 0);
robertphillips1f3923e2016-07-21 07:17:54 -0700466
halcanarya1f1ee92015-02-20 06:17:26 -0800467 if (flip) {
468 // Skia generally uses the top left as the origin but PDF
469 // natively has the origin at the bottom left. This matrix
470 // corrects for that. But that only needs to be done once, we
471 // don't do it when layering.
472 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
473 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
474 } else {
475 fInitialTransform.setIdentity();
476 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000477}
478
479SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700480 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000481}
482
483void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700484 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000485}
486
halcanary3c35fb32016-06-30 11:55:07 -0700487void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000488 fGraphicStateResources.unrefAll();
489 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000490 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000491 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000492}
493
reedf70b5312016-03-04 16:36:20 -0800494void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
495 SkData* value) {
496 if (0 == rect.width() && 0 == rect.height()) {
497 handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
498 } else {
499 SkPath path;
500 path.addRect(rect);
501 handlePathAnnotation(path, d, key, value);
502 }
503}
504
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000505void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000506 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700507 replace_srcmode_on_opaque_paint(&newPaint);
508
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000509 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000510 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000511 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000512}
513
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000514void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700515 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000516 if (!contentEntry) {
517 return;
518 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000519 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
520 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000521 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000522 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000523 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000524 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000525 inverse.mapRect(&bbox);
526
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000527 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000528 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000529 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000530}
531
halcanary682ee012016-01-28 10:59:34 -0800532void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700533 SkCanvas::PointMode mode,
534 size_t count,
535 const SkPoint* points,
536 const SkPaint& srcPaint) {
537 SkPaint passedPaint = srcPaint;
538 replace_srcmode_on_opaque_paint(&passedPaint);
539
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000540 if (count == 0) {
541 return;
542 }
543
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000544 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
545 // We only use this when there's a path effect because of the overhead
546 // of multiple calls to setUpContentEntry it causes.
547 if (passedPaint.getPathEffect()) {
reed1e7f5e72016-04-27 07:49:17 -0700548 if (d.fRC->isEmpty()) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000549 return;
550 }
551 SkDraw pointDraw(d);
552 pointDraw.fDevice = this;
553 pointDraw.drawPoints(mode, count, points, passedPaint, true);
554 return;
555 }
556
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000557 const SkPaint* paint = &passedPaint;
558 SkPaint modifiedPaint;
559
560 if (mode == SkCanvas::kPoints_PointMode &&
561 paint->getStrokeCap() != SkPaint::kRound_Cap) {
562 modifiedPaint = *paint;
563 paint = &modifiedPaint;
564 if (paint->getStrokeWidth()) {
565 // PDF won't draw a single point with square/butt caps because the
566 // orientation is ambiguous. Draw a rectangle instead.
567 modifiedPaint.setStyle(SkPaint::kFill_Style);
568 SkScalar strokeWidth = paint->getStrokeWidth();
569 SkScalar halfStroke = SkScalarHalf(strokeWidth);
570 for (size_t i = 0; i < count; i++) {
571 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
572 r.inset(-halfStroke, -halfStroke);
573 drawRect(d, r, modifiedPaint);
574 }
575 return;
576 } else {
577 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
578 }
579 }
580
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000581 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000582 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000583 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000584 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000585
586 switch (mode) {
587 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000588 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000589 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000590 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000591 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000592 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000593 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000594 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000595 break;
596 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000597 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000598 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000599 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000600 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000601 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000602 &content.entry()->fContent);
603 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000604 }
605 break;
606 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000607 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
608 for (size_t i = 0; i < count; i++) {
609 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000610 &content.entry()->fContent);
611 SkPDFUtils::ClosePath(&content.entry()->fContent);
612 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000613 }
614 break;
615 default:
616 SkASSERT(false);
617 }
618}
619
halcanary8103a342016-03-08 15:10:16 -0800620static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800621 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700622 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700623 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700624
halcanaryece83922016-03-08 08:32:12 -0800625 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700626 border->reserve(3);
627 border->appendInt(0); // Horizontal corner radius.
628 border->appendInt(0); // Vertical corner radius.
629 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800630 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700631
halcanaryece83922016-03-08 08:32:12 -0800632 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700633 rect->reserve(4);
634 rect->appendScalar(translatedRect.fLeft);
635 rect->appendScalar(translatedRect.fTop);
636 rect->appendScalar(translatedRect.fRight);
637 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800638 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700639
halcanary8103a342016-03-08 15:10:16 -0800640 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700641}
642
halcanary8103a342016-03-08 15:10:16 -0800643static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700644 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700645 SkString url(static_cast<const char *>(urlData->data()),
646 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800647 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700648 action->insertName("S", "URI");
649 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800650 annotation->insertObject("A", std::move(action));
651 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700652}
653
halcanary8103a342016-03-08 15:10:16 -0800654static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
655 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700656 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700657 SkString name(static_cast<const char *>(nameData->data()),
658 nameData->size() - 1);
659 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800660 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700661}
662
halcanary682ee012016-01-28 10:59:34 -0800663void SkPDFDevice::drawRect(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700664 const SkRect& rect,
665 const SkPaint& srcPaint) {
666 SkPaint paint = srcPaint;
667 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000668 SkRect r = rect;
669 r.sort();
670
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000671 if (paint.getPathEffect()) {
reed1e7f5e72016-04-27 07:49:17 -0700672 if (d.fRC->isEmpty()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000673 return;
674 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000675 SkPath path;
676 path.addRect(r);
halcanary96fcdcc2015-08-27 07:41:13 -0700677 drawPath(d, path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000678 return;
679 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000680
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000681 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000682 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000683 return;
684 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000685 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000686 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000687 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000688}
689
halcanarya6814332015-05-27 08:53:36 -0700690void SkPDFDevice::drawRRect(const SkDraw& draw,
691 const SkRRect& rrect,
692 const SkPaint& srcPaint) {
693 SkPaint paint = srcPaint;
694 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000695 SkPath path;
696 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700697 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000698}
699
halcanarya6814332015-05-27 08:53:36 -0700700void SkPDFDevice::drawOval(const SkDraw& draw,
701 const SkRect& oval,
702 const SkPaint& srcPaint) {
703 SkPaint paint = srcPaint;
704 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700705 SkPath path;
706 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700707 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700708}
709
halcanary682ee012016-01-28 10:59:34 -0800710void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700711 const SkPath& origPath,
712 const SkPaint& srcPaint,
713 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000714 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700715 SkPaint paint = srcPaint;
716 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800717 SkPath modifiedPath;
718 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000719
720 SkMatrix matrix = *d.fMatrix;
721 if (prePathMatrix) {
722 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800723 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000724 pathPtr = &modifiedPath;
725 pathIsMutable = true;
726 }
halcanary682ee012016-01-28 10:59:34 -0800727 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000728 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000729 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000730 }
731 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000732
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000733 if (paint.getPathEffect()) {
reed1e7f5e72016-04-27 07:49:17 -0700734 if (d.fRC->isEmpty()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000735 return;
736 }
halcanary682ee012016-01-28 10:59:34 -0800737 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000738 pathPtr = &modifiedPath;
739 pathIsMutable = true;
740 }
halcanary682ee012016-01-28 10:59:34 -0800741 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000742
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000743 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -0700744 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000745 if (fill) {
746 noEffectPaint.setStyle(SkPaint::kFill_Style);
747 } else {
748 noEffectPaint.setStyle(SkPaint::kStroke_Style);
749 noEffectPaint.setStrokeWidth(0);
750 }
halcanary96fcdcc2015-08-27 07:41:13 -0700751 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000752 return;
753 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000754
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000755 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000756 return;
757 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000758
reed1e7f5e72016-04-27 07:49:17 -0700759 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000760 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000761 return;
762 }
halcanary8b2bc252015-10-06 09:41:47 -0700763 bool consumeDegeratePathSegments =
764 paint.getStyle() == SkPaint::kFill_Style ||
765 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
766 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000767 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -0700768 consumeDegeratePathSegments,
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000769 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000770 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000771 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000772}
773
halcanary7a14b312015-10-01 07:28:13 -0700774void SkPDFDevice::drawBitmapRect(const SkDraw& draw,
775 const SkBitmap& bitmap,
776 const SkRect* src,
777 const SkRect& dst,
778 const SkPaint& srcPaint,
779 SkCanvas::SrcRectConstraint constraint) {
halcanary66be6262016-03-21 13:01:34 -0700780 SkASSERT(false);
halcanary7a14b312015-10-01 07:28:13 -0700781}
782
783void SkPDFDevice::drawBitmap(const SkDraw& d,
784 const SkBitmap& bitmap,
785 const SkMatrix& matrix,
786 const SkPaint& srcPaint) {
halcanarya6814332015-05-27 08:53:36 -0700787 SkPaint paint = srcPaint;
788 if (bitmap.isOpaque()) {
789 replace_srcmode_on_opaque_paint(&paint);
790 }
791
reed1e7f5e72016-04-27 07:49:17 -0700792 if (d.fRC->isEmpty()) {
halcanary7a14b312015-10-01 07:28:13 -0700793 return;
794 }
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000795
halcanary7a14b312015-10-01 07:28:13 -0700796 SkMatrix transform = matrix;
797 transform.postConcat(*d.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700798 SkImageBitmap imageBitmap(bitmap);
799 this->internalDrawImage(
reed1e7f5e72016-04-27 07:49:17 -0700800 transform, d.fClipStack, d.fRC->bwRgn(), imageBitmap, paint);
halcanary7a14b312015-10-01 07:28:13 -0700801}
802
803void SkPDFDevice::drawSprite(const SkDraw& d,
804 const SkBitmap& bitmap,
805 int x,
806 int y,
807 const SkPaint& srcPaint) {
808 SkPaint paint = srcPaint;
809 if (bitmap.isOpaque()) {
810 replace_srcmode_on_opaque_paint(&paint);
811 }
812
reed1e7f5e72016-04-27 07:49:17 -0700813 if (d.fRC->isEmpty()) {
halcanary7a14b312015-10-01 07:28:13 -0700814 return;
815 }
816
817 SkMatrix matrix;
818 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
halcanarya50151d2016-03-25 11:57:49 -0700819 SkImageBitmap imageBitmap(bitmap);
820 this->internalDrawImage(
reed1e7f5e72016-04-27 07:49:17 -0700821 matrix, d.fClipStack, d.fRC->bwRgn(), imageBitmap, paint);
halcanary7a14b312015-10-01 07:28:13 -0700822}
823
824void SkPDFDevice::drawImage(const SkDraw& draw,
825 const SkImage* image,
826 SkScalar x,
827 SkScalar y,
828 const SkPaint& srcPaint) {
829 SkPaint paint = srcPaint;
830 if (!image) {
831 return;
832 }
833 if (image->isOpaque()) {
834 replace_srcmode_on_opaque_paint(&paint);
835 }
reed1e7f5e72016-04-27 07:49:17 -0700836 if (draw.fRC->isEmpty()) {
halcanary7a14b312015-10-01 07:28:13 -0700837 return;
838 }
839 SkMatrix transform = SkMatrix::MakeTrans(x, y);
840 transform.postConcat(*draw.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700841 SkImageBitmap imageBitmap(const_cast<SkImage*>(image));
842 this->internalDrawImage(
reed1e7f5e72016-04-27 07:49:17 -0700843 transform, draw.fClipStack, draw.fRC->bwRgn(), imageBitmap, paint);
halcanary7a14b312015-10-01 07:28:13 -0700844}
845
846void SkPDFDevice::drawImageRect(const SkDraw& draw,
847 const SkImage* image,
848 const SkRect* src,
849 const SkRect& dst,
850 const SkPaint& srcPaint,
851 SkCanvas::SrcRectConstraint constraint) {
halcanary66be6262016-03-21 13:01:34 -0700852 SkASSERT(false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000853}
854
halcanaryf0c30f52016-07-15 13:35:45 -0700855namespace {
856class GlyphPositioner {
857public:
858 GlyphPositioner(SkDynamicMemoryWStream* content,
859 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700860 bool wideChars,
861 bool defaultPositioning,
862 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700863 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700864 , fCurrentMatrixOrigin(origin)
865 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -0700866 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -0700867 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -0700868 }
halcanary4871f222016-08-26 13:17:44 -0700869 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700870 void flush() {
871 if (fInText) {
872 fContent->writeText("> Tj\n");
873 fInText = false;
874 }
875 }
halcanary4871f222016-08-26 13:17:44 -0700876 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -0700877 SkScalar advanceWidth,
878 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -0700879 if (!fInitialized) {
880 // Flip the text about the x-axis to account for origin swap and include
881 // the passed parameters.
882 fContent->writeText("1 0 ");
883 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
884 fContent->writeText(" -1 ");
885 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
886 fContent->writeText(" ");
887 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
888 fContent->writeText(" Tm\n");
889 fCurrentMatrixOrigin.set(0.0f, 0.0f);
890 fInitialized = true;
891 }
halcanary4ed2f012016-08-15 18:40:07 -0700892 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -0700893 SkPoint position = xy - fCurrentMatrixOrigin;
894 if (position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -0700895 this->flush();
halcanary4871f222016-08-26 13:17:44 -0700896 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700897 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -0700898 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700899 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -0700900 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -0700901 fXAdvance = 0;
902 }
903 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -0700904 }
905 if (!fInText) {
906 fContent->writeText("<");
907 fInText = true;
908 }
909 if (fWideChars) {
910 SkPDFUtils::WriteUInt16BE(fContent, glyph);
911 } else {
912 SkASSERT(0 == glyph >> 8);
913 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
914 }
halcanaryf0c30f52016-07-15 13:35:45 -0700915 }
916
917private:
918 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -0700919 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -0700920 SkScalar fXAdvance = 0.0f;
921 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -0700922 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -0700923 bool fInText = false;
924 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -0700925 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -0700926};
halcanaryf59d18a2016-09-16 14:44:57 -0700927
928/** Given the m-to-n glyph-to-character mapping data (as returned by
929 harfbuzz), iterate over the clusters. */
930class Clusterator {
931public:
932 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
933 explicit Clusterator(uint32_t glyphCount)
934 : fClusters(nullptr)
935 , fUtf8Text(nullptr)
936 , fGlyphCount(glyphCount)
937 , fTextByteLength(0) {}
938 // The clusters[] array is an array of offsets into utf8Text[],
939 // one offset for each glyph. See SkTextBlobBuilder for more info.
940 Clusterator(const uint32_t* clusters,
941 const char* utf8Text,
942 uint32_t glyphCount,
943 uint32_t textByteLength)
944 : fClusters(clusters)
945 , fUtf8Text(utf8Text)
946 , fGlyphCount(glyphCount)
947 , fTextByteLength(textByteLength) {
948 // This is a cheap heuristic for /ReversedChars which seems to
949 // work for clusters produced by HarfBuzz, which either
950 // increase from zero (LTR) or decrease to zero (RTL).
951 // "ReversedChars" is how PDF deals with RTL text.
952 fReversedChars =
953 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
954 }
955 struct Cluster {
956 const char* fUtf8Text;
957 uint32_t fTextByteLength;
958 uint32_t fGlyphIndex;
959 uint32_t fGlyphCount;
960 explicit operator bool() const { return fGlyphCount != 0; }
961 };
962 // True if this looks like right-to-left text.
963 bool reversedChars() const { return fReversedChars; }
964 Cluster next() {
965 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
966 // These glyphs have no text. Treat as one "cluster".
967 uint32_t glyphCount = fGlyphCount;
968 fGlyphCount = 0;
969 return Cluster{nullptr, 0, 0, glyphCount};
970 }
971 if (fGlyphCount == 0 || fTextByteLength == 0) {
972 return Cluster{nullptr, 0, 0, 0}; // empty
973 }
974 SkASSERT(fUtf8Text);
975 SkASSERT(fClusters);
976 uint32_t cluster = fClusters[0];
977 if (cluster >= fTextByteLength) {
978 return Cluster{nullptr, 0, 0, 0}; // bad input.
979 }
980 uint32_t glyphsInCluster = 1;
981 while (glyphsInCluster < fGlyphCount &&
982 fClusters[glyphsInCluster] == cluster) {
983 ++glyphsInCluster;
984 }
985 SkASSERT(glyphsInCluster <= fGlyphCount);
986 uint32_t textLength = 0;
987 if (glyphsInCluster == fGlyphCount) {
988 // consumes rest of glyphs and rest of text
989 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
990 textLength = fTextByteLength - cluster;
991 } else { // RTL text; last cluster.
992 SkASSERT(fPreviousCluster < fTextByteLength);
993 if (fPreviousCluster <= cluster) { // bad input.
994 return Cluster{nullptr, 0, 0, 0};
995 }
996 textLength = fPreviousCluster - cluster;
997 }
998 fGlyphCount = 0;
999 return Cluster{fUtf8Text + cluster,
1000 textLength,
1001 fGlyphIndex,
1002 glyphsInCluster};
1003 }
1004 SkASSERT(glyphsInCluster < fGlyphCount);
1005 uint32_t nextCluster = fClusters[glyphsInCluster];
1006 if (nextCluster >= fTextByteLength) {
1007 return Cluster{nullptr, 0, 0, 0}; // bad input.
1008 }
1009 if (nextCluster > cluster) { // LTR text
1010 if (kInvalidCluster != fPreviousCluster) {
1011 return Cluster{nullptr, 0, 0, 0}; // bad input.
1012 }
1013 textLength = nextCluster - cluster;
1014 } else { // RTL text
1015 SkASSERT(nextCluster < cluster);
1016 if (kInvalidCluster == fPreviousCluster) { // first cluster
1017 textLength = fTextByteLength - cluster;
1018 } else { // later cluster
1019 if (fPreviousCluster <= cluster) {
1020 return Cluster{nullptr, 0, 0, 0}; // bad input.
1021 }
1022 textLength = fPreviousCluster - cluster;
1023 }
1024 fPreviousCluster = cluster;
1025 }
1026 uint32_t glyphIndex = fGlyphIndex;
1027 fGlyphCount -= glyphsInCluster;
1028 fGlyphIndex += glyphsInCluster;
1029 fClusters += glyphsInCluster;
1030 return Cluster{fUtf8Text + cluster,
1031 textLength,
1032 glyphIndex,
1033 glyphsInCluster};
1034 }
1035
1036private:
1037 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1038 const uint32_t* fClusters;
1039 const char* fUtf8Text;
1040 uint32_t fGlyphCount;
1041 uint32_t fTextByteLength;
1042 uint32_t fGlyphIndex = 0;
1043 uint32_t fPreviousCluster = kInvalidCluster;
1044 bool fReversedChars = false;
1045};
1046
1047struct TextStorage {
1048 SkAutoTMalloc<char> fUtf8textStorage;
1049 SkAutoTMalloc<uint32_t> fClusterStorage;
1050 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1051};
halcanaryf0c30f52016-07-15 13:35:45 -07001052} // namespace
1053
halcanaryf59d18a2016-09-16 14:44:57 -07001054/** Given some unicode text (as passed to drawText(), convert to
1055 glyphs (via primitive shaping), while preserving
1056 glyph-to-character mapping information. */
1057static Clusterator make_clusterator(
1058 const void* sourceText,
1059 size_t sourceByteCount,
1060 const SkPaint& paint,
1061 TextStorage* storage,
1062 int glyphCount) {
1063 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1064 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1065 SkASSERT(glyphCount > 0);
1066 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1067 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1068 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1069 uint32_t* clusters = storage->fClusterStorage.get();
1070 uint32_t utf8ByteCount = 0;
1071 const char* utf8Text = nullptr;
1072 switch (paint.getTextEncoding()) {
1073 case SkPaint::kUTF8_TextEncoding: {
1074 const char* txtPtr = (const char*)sourceText;
1075 for (int i = 0; i < glyphCount; ++i) {
1076 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1077 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1078 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1079 }
1080 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1081 utf8ByteCount = SkToU32(sourceByteCount);
1082 utf8Text = (const char*)sourceText;
1083 break;
1084 }
1085 case SkPaint::kUTF16_TextEncoding: {
1086 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1087 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1088 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1089 storage->fUtf8textStorage.reset(utf8ByteCount);
1090 char* txtPtr = storage->fUtf8textStorage.get();
1091 utf8Text = txtPtr;
1092 int clusterIndex = 0;
1093 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1094 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1095 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1096 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1097 }
1098 SkASSERT(clusterIndex == glyphCount);
1099 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1100 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1101 break;
1102 }
1103 case SkPaint::kUTF32_TextEncoding: {
1104 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1105 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1106 SkASSERT(glyphCount == utf32count);
1107 for (int i = 0; i < utf32count; ++i) {
1108 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1109 }
1110 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1111 char* txtPtr = storage->fUtf8textStorage.get();
1112 utf8Text = txtPtr;
1113 for (int i = 0; i < utf32count; ++i) {
1114 clusters[i] = SkToU32(txtPtr - utf8Text);
1115 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1116 }
1117 break;
1118 }
1119 default:
1120 SkDEBUGFAIL("");
1121 break;
1122 }
1123 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1124}
1125
halcanary66a82f32015-10-12 13:05:04 -07001126static void draw_transparent_text(SkPDFDevice* device,
1127 const SkDraw& d,
1128 const void* text, size_t len,
1129 SkScalar x, SkScalar y,
1130 const SkPaint& srcPaint) {
halcanary4871f222016-08-26 13:17:44 -07001131 sk_sp<SkTypeface> defaultFace = SkTypeface::MakeDefault();
1132 if (!SkPDFFont::CanEmbedTypeface(defaultFace.get(), device->getCanon())) {
halcanary4ed2f012016-08-15 18:40:07 -07001133 SkDebugf("SkPDF: default typeface should be embeddable");
halcanary66a82f32015-10-12 13:05:04 -07001134 return; // Avoid infinite loop in release.
1135 }
halcanary4871f222016-08-26 13:17:44 -07001136 SkPaint transparent;
1137 transparent.setTypeface(std::move(defaultFace));
halcanary66a82f32015-10-12 13:05:04 -07001138 transparent.setTextSize(srcPaint.getTextSize());
1139 transparent.setColor(SK_ColorTRANSPARENT);
1140 switch (srcPaint.getTextEncoding()) {
1141 case SkPaint::kGlyphID_TextEncoding: {
1142 // Since a glyphId<->Unicode mapping is typeface-specific,
1143 // map back to Unicode first.
1144 size_t glyphCount = len / 2;
1145 SkAutoTMalloc<SkUnichar> unichars(glyphCount);
1146 srcPaint.glyphsToUnichars(
1147 (const uint16_t*)text, SkToInt(glyphCount), &unichars[0]);
1148 transparent.setTextEncoding(SkPaint::kUTF32_TextEncoding);
halcanary4ed2f012016-08-15 18:40:07 -07001149 // TODO(halcanary): deal with case where default typeface
1150 // does not have glyphs for these unicode code points.
halcanary66a82f32015-10-12 13:05:04 -07001151 device->drawText(d, &unichars[0],
1152 glyphCount * sizeof(SkUnichar),
1153 x, y, transparent);
1154 break;
1155 }
1156 case SkPaint::kUTF8_TextEncoding:
1157 case SkPaint::kUTF16_TextEncoding:
1158 case SkPaint::kUTF32_TextEncoding:
1159 transparent.setTextEncoding(srcPaint.getTextEncoding());
1160 device->drawText(d, text, len, x, y, transparent);
1161 break;
1162 default:
1163 SkFAIL("unknown text encoding");
1164 }
1165}
1166
halcanaryf59d18a2016-09-16 14:44:57 -07001167static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1168 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1169}
1170
halcanaryc2f9ec12016-09-12 08:55:29 -07001171static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1172 wStream->writeText("/");
1173 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1174 wStream->write(&prefix, 1);
1175 wStream->writeDecAsText(fontIndex);
1176 wStream->writeText(" ");
1177 SkPDFUtils::AppendScalar(textSize, wStream);
1178 wStream->writeText(" Tf\n");
1179}
1180
halcanary4ed2f012016-08-15 18:40:07 -07001181void SkPDFDevice::internalDrawText(
1182 const SkDraw& d, const void* sourceText, size_t sourceByteCount,
1183 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001184 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1185 uint32_t textByteLength, const char* utf8Text) {
halcanary4ed2f012016-08-15 18:40:07 -07001186 NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1187 if (srcPaint.getMaskFilter() != nullptr) {
1188 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1189 // making text unreadable (e.g. same text twice when using CSS shadows).
1190 return;
1191 }
halcanaryea17dfe2016-08-24 09:20:57 -07001192 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1193 if (srcPaint.isVerticalText()) {
1194 // Don't pretend we support drawing vertical text. It is not
1195 // clear to me how to switch to "vertical writing" mode in PDF.
1196 // Currently neither Chromium or Android set this flag.
1197 // https://bug.skia.org/5665
1198 return;
1199 }
halcanaryf59d18a2016-09-16 14:44:57 -07001200 if (0 == sourceByteCount || !sourceText) {
1201 return;
halcanarye06ca962016-09-09 05:34:55 -07001202 }
halcanary4ed2f012016-08-15 18:40:07 -07001203 SkPaint paint = calculate_text_paint(srcPaint);
1204 replace_srcmode_on_opaque_paint(&paint);
1205 if (!paint.getTypeface()) {
1206 paint.setTypeface(SkTypeface::MakeDefault());
1207 }
1208 SkTypeface* typeface = paint.getTypeface();
1209 if (!typeface) {
1210 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1211 return;
1212 }
halcanary4871f222016-08-26 13:17:44 -07001213
1214 const SkAdvancedTypefaceMetrics* metrics =
1215 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1216 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001217 return;
1218 }
halcanary2bd295e2016-09-16 08:15:56 -07001219 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1220 if (glyphCount <= 0) {
1221 return;
1222 }
halcanary4871f222016-08-26 13:17:44 -07001223 // TODO(halcanary): use metrics->fGlyphToUnicode to check Unicode mapping.
halcanary4ed2f012016-08-15 18:40:07 -07001224 if (!SkPDFFont::CanEmbedTypeface(typeface, fDocument->canon())) {
1225 SkPath path; // https://bug.skia.org/3866
halcanary2bd295e2016-09-16 08:15:56 -07001226 switch (positioning) {
1227 case SkTextBlob::kDefault_Positioning:
1228 srcPaint.getTextPath(sourceText, sourceByteCount,
1229 offset.x(), offset.y(), &path);
1230 break;
1231 case SkTextBlob::kHorizontal_Positioning: {
1232 SkAutoTMalloc<SkPoint> positionsBuffer(glyphCount);
1233 for (int i = 0; i < glyphCount; ++i) {
1234 positionsBuffer[i] = offset + SkPoint{pos[i], 0};
1235 }
1236 srcPaint.getPosTextPath(sourceText, sourceByteCount,
1237 &positionsBuffer[0], &path);
1238 break;
1239 }
1240 case SkTextBlob::kFull_Positioning: {
1241 SkAutoTMalloc<SkPoint> positionsBuffer(glyphCount);
1242 for (int i = 0; i < glyphCount; ++i) {
1243 positionsBuffer[i] = offset + SkPoint{pos[2 * i], pos[2 * i + 1]};
1244 }
1245 srcPaint.getPosTextPath(sourceText, sourceByteCount,
1246 &positionsBuffer[0], &path);
1247 break;
1248 }
1249 }
robertphillips5ba165e2016-08-15 15:36:58 -07001250 this->drawPath(d, path, srcPaint, &SkMatrix::I(), true);
1251 // Draw text transparently to make it copyable/searchable/accessable.
halcanary4ed2f012016-08-15 18:40:07 -07001252 draw_transparent_text(this, d, sourceText, sourceByteCount,
1253 offset.x(), offset.y(), paint);
robertphillips5ba165e2016-08-15 15:36:58 -07001254 return;
1255 }
halcanary3b294d52016-09-16 13:21:08 -07001256
halcanaryf59d18a2016-09-16 14:44:57 -07001257 // These three heap buffers are only used in the case where no glyphs
1258 // are passed to drawText() (most clients pass glyphs or a textblob).
1259 TextStorage storage;
1260 const SkGlyphID* glyphs = nullptr;
1261 Clusterator clusterator;
1262 if (textByteLength > 0) {
1263 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1264 glyphs = (const SkGlyphID*)sourceText;
1265 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1266 SkASSERT(clusters);
1267 SkASSERT(utf8Text);
1268 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1269 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1270 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1271 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1272 glyphs = (const SkGlyphID*)sourceText;
1273 clusterator = Clusterator(SkToU32(glyphCount));
1274 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1275 SkASSERT(nullptr == clusters);
1276 SkASSERT(nullptr == utf8Text);
1277 } else {
1278 SkASSERT(nullptr == clusters);
1279 SkASSERT(nullptr == utf8Text);
1280 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1281 &storage, glyphCount);
1282 glyphs = storage.fGlyphStorage;
1283 }
halcanary4ed2f012016-08-15 18:40:07 -07001284 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001285 paint.setHinting(SkPaint::kNo_Hinting);
halcanary4ed2f012016-08-15 18:40:07 -07001286 SkAutoGlyphCache glyphCache(paint, nullptr, nullptr);
1287
1288 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001289 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1290 SkPaint::kCenter_Align == alignment ? -0.5f :
1291 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001292 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001293 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001294 for (int i = 0; i < glyphCount; ++i) {
1295 advance += glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
1296 }
halcanary4871f222016-08-26 13:17:44 -07001297 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001298 }
halcanary4ed2f012016-08-15 18:40:07 -07001299 ScopedContentEntry content(this, d, paint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001300 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001301 return;
1302 }
halcanary4ed2f012016-08-15 18:40:07 -07001303 SkDynamicMemoryWStream* out = &content.entry()->fContent;
halcanary4871f222016-08-26 13:17:44 -07001304 SkScalar textSize = paint.getTextSize();
halcanaryf59d18a2016-09-16 14:44:57 -07001305 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
halcanary4871f222016-08-26 13:17:44 -07001306
halcanary4871f222016-08-26 13:17:44 -07001307 out->writeText("BT\n");
1308 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1309
halcanaryf59d18a2016-09-16 14:44:57 -07001310 const SkGlyphID maxGlyphID = metrics->fLastGlyphID;
halcanaryc2f9ec12016-09-12 08:55:29 -07001311 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
halcanaryf59d18a2016-09-16 14:44:57 -07001312 if (clusterator.reversedChars()) {
1313 out->writeText("/ReversedChars BMC\n");
1314 }
1315 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
halcanary4ed2f012016-08-15 18:40:07 -07001316 GlyphPositioner glyphPositioner(out,
1317 paint.getTextSkewX(),
halcanaryc2f9ec12016-09-12 08:55:29 -07001318 multiByteGlyphs,
halcanary4ed2f012016-08-15 18:40:07 -07001319 defaultPositioning,
1320 offset);
halcanaryc2f9ec12016-09-12 08:55:29 -07001321 SkPDFFont* font = nullptr;
halcanaryf59d18a2016-09-16 14:44:57 -07001322
1323 while (Clusterator::Cluster c = clusterator.next()) {
1324 int index = c.fGlyphIndex;
1325 int glyphLimit = index + c.fGlyphCount;
1326
1327 bool actualText = false;
1328 SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1329 if (c.fUtf8Text) { // real cluster
1330 // Check if `/ActualText` needed.
1331 const char* textPtr = c.fUtf8Text;
1332 // TODO(halcanary): validate utf8 input.
1333 SkUnichar unichar = SkUTF8_NextUnichar(&textPtr);
1334 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1335 if (textPtr < textEnd || // more characters left
1336 glyphLimit > index + 1 || // toUnicode wouldn't work
1337 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1338 {
1339 glyphPositioner.flush();
1340 out->writeText("/Span<</ActualText <");
1341 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1342 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1343 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1344 while (textPtr < textEnd) {
1345 unichar = SkUTF8_NextUnichar(&textPtr);
1346 SkPDFUtils::WriteUTF16beHex(out, unichar);
1347 }
1348 out->writeText("> >> BDC\n"); // begin marked-content sequence
1349 // with an associated property list.
1350 actualText = true;
robertphillips5ba165e2016-08-15 15:36:58 -07001351 }
1352 }
halcanaryf59d18a2016-09-16 14:44:57 -07001353 for (; index < glyphLimit; ++index) {
1354 SkGlyphID gid = glyphs[index];
1355 if (gid > maxGlyphID) {
1356 continue;
1357 }
1358 if (!font || !font->hasGlyph(gid)) {
1359 // Not yet specified font or need to switch font.
1360 int fontIndex = this->getFontResourceIndex(typeface, gid);
1361 // All preconditions for SkPDFFont::GetFontResource are met.
1362 SkASSERT(fontIndex >= 0);
1363 if (fontIndex < 0) {
1364 return;
1365 }
1366 glyphPositioner.flush();
1367 update_font(out, fontIndex, textSize);
1368 font = fFontResources[fontIndex];
1369 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1370 if (!font) {
1371 return;
1372 }
1373 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1374 }
1375 SkPoint xy{0, 0};
1376 SkScalar advance{0};
1377 if (!defaultPositioning) {
1378 advance = glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1379 xy = SkTextBlob::kFull_Positioning == positioning
1380 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1381 : SkPoint{pos[index], 0};
1382 if (alignment != SkPaint::kLeft_Align) {
1383 xy.offset(alignmentFactor * advance, 0);
1384 }
1385 }
1386 font->noteGlyphUsage(gid);
1387 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1388 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1389 }
robertphillips5ba165e2016-08-15 15:36:58 -07001390 }
halcanary4ed2f012016-08-15 18:40:07 -07001391}
1392
1393void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1394 SkScalar x, SkScalar y, const SkPaint& paint) {
1395 this->internalDrawText(d, text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001396 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001397}
1398
1399void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1400 const SkScalar pos[], int scalarsPerPos,
1401 const SkPoint& offset, const SkPaint& paint) {
1402 this->internalDrawText(d, text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001403 offset, paint, nullptr, 0, nullptr);
1404}
1405
1406void SkPDFDevice::drawTextBlob(const SkDraw& draw, const SkTextBlob* blob, SkScalar x, SkScalar y,
1407 const SkPaint &paint, SkDrawFilter* drawFilter) {
1408 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1409 SkPaint runPaint(paint);
1410 it.applyFontToPaint(&runPaint);
1411 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1412 continue;
1413 }
1414 runPaint.setFlags(this->filterTextFlags(runPaint));
1415 SkPoint offset = it.offset() + SkPoint{x, y};
1416 this->internalDrawText(draw, it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
1417 it.pos(), it.positioning(), offset, runPaint,
1418 it.clusters(), it.textSize(), it.text());
1419 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001420}
1421
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001422void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001423 int vertexCount, const SkPoint verts[],
1424 const SkPoint texs[], const SkColor colors[],
1425 SkXfermode* xmode, const uint16_t indices[],
1426 int indexCount, const SkPaint& paint) {
reed1e7f5e72016-04-27 07:49:17 -07001427 if (d.fRC->isEmpty()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001428 return;
1429 }
reed@google.com85e143c2013-12-30 15:51:25 +00001430 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001431}
1432
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001433void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1434 int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001435 SkASSERT(!paint.getImageFilter());
1436
reed7503d602016-07-15 14:23:29 -07001437 // Check if the source device is really a bitmapdevice (because that's what we returned
1438 // from createDevice (likely due to an imagefilter)
1439 SkPixmap pmap;
1440 if (device->peekPixels(&pmap)) {
1441 SkBitmap bitmap;
1442 bitmap.installPixels(pmap);
reedcf5c8462016-07-20 12:28:40 -07001443 this->drawSprite(d, bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001444 return;
1445 }
1446
fmalita6987dca2014-11-13 08:33:37 -08001447 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001448 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001449
1450 SkScalar scalarX = SkIntToScalar(x);
1451 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001452 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1453 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001454 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001455 }
halcanary91fcb3e2016-03-04 13:53:22 -08001456 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1457 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001458 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001459 }
halcanary91fcb3e2016-03-04 13:53:22 -08001460 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1461 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001462 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001463 }
1464
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001465 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001466 return;
1467 }
1468
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001469 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001470 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
reed1e7f5e72016-04-27 07:49:17 -07001471 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001472 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001473 return;
1474 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001475 if (content.needShape()) {
1476 SkPath shape;
1477 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001478 SkIntToScalar(device->width()),
1479 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001480 content.setShape(shape);
1481 }
1482 if (!content.needSource()) {
1483 return;
1484 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001485
halcanary4b1e17e2016-07-27 14:49:46 -07001486 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001487 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001488 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001489}
1490
reede8f30622016-03-23 18:59:25 -07001491sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1492 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001493}
1494
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001495
halcanary8103a342016-03-08 15:10:16 -08001496sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001497 SkTDArray<SkPDFObject*> fonts;
1498 fonts.setReserve(fFontResources.count());
1499 for (SkPDFFont* font : fFontResources) {
1500 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001501 }
halcanary8103a342016-03-08 15:10:16 -08001502 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001503 &fGraphicStateResources,
1504 &fShaderResources,
1505 &fXObjectResources,
1506 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001507}
1508
halcanary8103a342016-03-08 15:10:16 -08001509sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001510 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001511 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001512 mediaBox->appendInt(0);
1513 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001514 mediaBox->appendInt(fPageSize.width());
1515 mediaBox->appendInt(fPageSize.height());
1516 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001517}
1518
mtklein5f939ab2016-03-16 10:28:35 -07001519std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001520 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001521 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001522 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001523 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001524
halcanaryafdc1772016-08-23 09:02:12 -07001525 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001526 for (const auto& entry : fContentEntries) {
1527 SkPoint translation;
1528 translation.iset(this->getOrigin());
1529 translation.negate();
1530 gsState.updateClip(entry.fState.fClipStack, entry.fState.fClipRegion,
1531 translation);
1532 gsState.updateMatrix(entry.fState.fMatrix);
1533 gsState.updateDrawingState(entry.fState);
1534
halcanaryafdc1772016-08-23 09:02:12 -07001535 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001536 }
1537 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001538 if (buffer.bytesWritten() > 0) {
1539 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1540 } else {
1541 return skstd::make_unique<SkMemoryStream>();
1542 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001543}
1544
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001545/* Draws an inverse filled path by using Path Ops to compute the positive
1546 * inverse using the current clip as the inverse bounds.
1547 * Return true if this was an inverse path and was properly handled,
1548 * otherwise returns false and the normal drawing routine should continue,
1549 * either as a (incorrect) fallback or because the path was not inverse
1550 * in the first place.
1551 */
1552bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001553 const SkPaint& paint, bool pathIsMutable,
1554 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001555 if (!origPath.isInverseFillType()) {
1556 return false;
1557 }
1558
reed1e7f5e72016-04-27 07:49:17 -07001559 if (d.fRC->isEmpty()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001560 return false;
1561 }
1562
1563 SkPath modifiedPath;
1564 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1565 SkPaint noInversePaint(paint);
1566
1567 // Merge stroking operations into final path.
1568 if (SkPaint::kStroke_Style == paint.getStyle() ||
1569 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1570 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1571 if (doFillPath) {
1572 noInversePaint.setStyle(SkPaint::kFill_Style);
1573 noInversePaint.setStrokeWidth(0);
1574 pathPtr = &modifiedPath;
1575 } else {
1576 // To be consistent with the raster output, hairline strokes
1577 // are rendered as non-inverted.
1578 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001579 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001580 return true;
1581 }
1582 }
1583
1584 // Get bounds of clip in current transform space
1585 // (clip bounds are given in device space).
1586 SkRect bounds;
1587 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001588 SkMatrix totalMatrix = *d.fMatrix;
1589 if (prePathMatrix) {
1590 totalMatrix.preConcat(*prePathMatrix);
1591 }
1592 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001593 return false;
1594 }
reed1e7f5e72016-04-27 07:49:17 -07001595 bounds.set(d.fRC->getBounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001596 transformInverse.mapRect(&bounds);
1597
1598 // Extend the bounds by the line width (plus some padding)
1599 // so the edge doesn't cause a visible stroke.
1600 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1601 paint.getStrokeWidth() + SK_Scalar1);
1602
1603 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1604 return false;
1605 }
1606
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001607 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001608 return true;
1609}
1610
reedf70b5312016-03-04 16:36:20 -08001611void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
epoger@google.comb58772f2013-03-08 09:09:10 +00001612 const SkMatrix& matrix,
reedf70b5312016-03-04 16:36:20 -08001613 const char key[], SkData* value) {
1614 if (!value) {
1615 return;
epoger@google.comb58772f2013-03-08 09:09:10 +00001616 }
reedf70b5312016-03-04 16:36:20 -08001617
1618 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1619 SkPoint transformedPoint;
1620 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1621 fNamedDestinations.emplace_back(value, transformedPoint);
1622 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001623}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001624
reedf70b5312016-03-04 16:36:20 -08001625void SkPDFDevice::handlePathAnnotation(const SkPath& path,
wangxianzhuef6c50a2015-09-17 20:38:02 -07001626 const SkDraw& d,
reedf70b5312016-03-04 16:36:20 -08001627 const char key[], SkData* value) {
1628 if (!value) {
1629 return;
1630 }
wangxianzhuef6c50a2015-09-17 20:38:02 -07001631
1632 SkPath transformedPath = path;
1633 transformedPath.transform(*d.fMatrix);
1634 SkRasterClip clip = *d.fRC;
senorblancoafc7cce2016-02-02 18:44:15 -08001635 clip.op(transformedPath, SkIRect::MakeWH(width(), height()), SkRegion::kIntersect_Op,
1636 false);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001637 SkRect transformedRect = SkRect::Make(clip.getBounds());
1638
reedf70b5312016-03-04 16:36:20 -08001639 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001640 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001641 fLinkToURLs.emplace_back(transformedRect, value);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001642 }
reedf70b5312016-03-04 16:36:20 -08001643 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
reed16108352016-03-03 09:14:36 -08001644 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001645 fLinkToDestinations.emplace_back(transformedRect, value);
reed16108352016-03-03 09:14:36 -08001646 }
reed16108352016-03-03 09:14:36 -08001647 }
halcanary438de492015-04-28 06:21:01 -07001648}
1649
wangxianzhuef6c50a2015-09-17 20:38:02 -07001650void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1651 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001652 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001653 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001654 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001655 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001656 }
halcanary91fcb3e2016-03-04 13:53:22 -08001657 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001658 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001659 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001660 array->appendObject(
1661 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001662 }
1663}
epoger@google.comb58772f2013-03-08 09:09:10 +00001664
halcanary6d622702015-03-25 08:45:42 -07001665void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001666 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001667 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001668 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001669 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001670 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001671 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001672 pdfDest->appendScalar(p.x());
1673 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001674 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001675 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001676 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001677 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001678}
1679
halcanary4b1e17e2016-07-27 14:49:46 -07001680sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001681 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001682 if (!fInitialTransform.isIdentity()) {
1683 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001684 SkDEBUGFAIL("Layer initial transform should be invertible.");
1685 inverseTransform.reset();
1686 }
1687 }
halcanary4b1e17e2016-07-27 14:49:46 -07001688 sk_sp<SkPDFObject> xobject =
1689 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001690 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001691 // We always draw the form xobjects that we create back into the device, so
1692 // we simply preserve the font usage instead of pulling it out and merging
1693 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001694 this->cleanUp(); // Reset this device to have no content.
1695 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001696 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001697}
1698
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001699void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001700 sk_sp<SkPDFObject> mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001701 const SkClipStack* clipStack,
1702 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001703 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001704 bool invertClip) {
1705 if (clipRegion.isEmpty() && !invertClip) {
1706 return;
1707 }
1708
halcanary4b1e17e2016-07-27 14:49:46 -07001709 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001710 std::move(mask), invertClip,
1711 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001712
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001713 SkMatrix identity;
1714 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001715 SkPaint paint;
1716 paint.setXfermodeMode(mode);
1717 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001718 if (!content.entry()) {
1719 return;
1720 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001721 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001722 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001723 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001724
halcanary1437c1e2016-03-13 18:30:24 -07001725 // Call makeNoSmaskGraphicState() instead of
1726 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1727 // can deduplicate.
halcanary989da4a2016-03-21 14:33:17 -07001728 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001729 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001730 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001731}
1732
halcanary2be7e012016-03-28 11:58:08 -07001733SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001734 const SkRegion& clipRegion,
1735 const SkMatrix& matrix,
1736 const SkPaint& paint,
1737 bool hasText,
halcanarydabd4f02016-08-03 11:16:56 -07001738 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001739 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001740 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001741 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001742 }
1743
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001744 // The clip stack can come from an SkDraw where it is technically optional.
1745 SkClipStack synthesizedClipStack;
halcanary96fcdcc2015-08-27 07:41:13 -07001746 if (clipStack == nullptr) {
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001747 if (clipRegion == fExistingClipRegion) {
1748 clipStack = &fExistingClipStack;
1749 } else {
1750 // GraphicStackState::updateClip expects the clip stack to have
1751 // fExistingClip as a prefix, so start there, then set the clip
1752 // to the passed region.
1753 synthesizedClipStack = fExistingClipStack;
1754 SkPath clipPath;
1755 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001756 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1757 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001758 clipStack = &synthesizedClipStack;
1759 }
1760 }
1761
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001762 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1763 if (paint.getXfermode()) {
1764 paint.getXfermode()->asMode(&xfermode);
1765 }
1766
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001767 // For the following modes, we want to handle source and destination
1768 // separately, so make an object of what's already there.
1769 if (xfermode == SkXfermode::kClear_Mode ||
1770 xfermode == SkXfermode::kSrc_Mode ||
1771 xfermode == SkXfermode::kSrcIn_Mode ||
1772 xfermode == SkXfermode::kDstIn_Mode ||
1773 xfermode == SkXfermode::kSrcOut_Mode ||
1774 xfermode == SkXfermode::kDstOut_Mode ||
1775 xfermode == SkXfermode::kSrcATop_Mode ||
1776 xfermode == SkXfermode::kDstATop_Mode ||
1777 xfermode == SkXfermode::kModulate_Mode) {
1778 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001779 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001780 SkASSERT(isContentEmpty());
1781 } else if (xfermode != SkXfermode::kSrc_Mode &&
1782 xfermode != SkXfermode::kSrcOut_Mode) {
1783 // Except for Src and SrcOut, if there isn't anything already there,
1784 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001785 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001786 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001787 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001788 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001789 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001790
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001791 // Dst xfer mode doesn't draw source at all.
1792 if (xfermode == SkXfermode::kDst_Mode) {
halcanary96fcdcc2015-08-27 07:41:13 -07001793 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001794 }
1795
halcanary2be7e012016-03-28 11:58:08 -07001796 SkPDFDevice::ContentEntry* entry;
1797 if (fContentEntries.back() && fContentEntries.back()->fContent.getOffset() == 0) {
1798 entry = fContentEntries.back();
1799 } else if (xfermode != SkXfermode::kDstOver_Mode) {
1800 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001801 } else {
halcanary2be7e012016-03-28 11:58:08 -07001802 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001803 }
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001804 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001805 hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001806 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001807}
1808
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001809void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
halcanarydabd4f02016-08-03 11:16:56 -07001810 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001811 SkPath* shape) {
1812 if (xfermode != SkXfermode::kClear_Mode &&
1813 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001814 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001815 xfermode != SkXfermode::kSrcIn_Mode &&
1816 xfermode != SkXfermode::kDstIn_Mode &&
1817 xfermode != SkXfermode::kSrcOut_Mode &&
1818 xfermode != SkXfermode::kDstOut_Mode &&
1819 xfermode != SkXfermode::kSrcATop_Mode &&
1820 xfermode != SkXfermode::kDstATop_Mode &&
1821 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001822 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001823 return;
1824 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001825 if (xfermode == SkXfermode::kDstOver_Mode) {
1826 SkASSERT(!dst);
halcanary2be7e012016-03-28 11:58:08 -07001827 if (fContentEntries.front()->fContent.getOffset() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001828 // For DstOver, an empty content entry was inserted before the rest
1829 // of the content entries. If nothing was drawn, it needs to be
1830 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001831 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001832 }
1833 return;
1834 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001835 if (!dst) {
1836 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1837 xfermode == SkXfermode::kSrcOut_Mode);
1838 return;
1839 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001840
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001841 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001842 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001843 // Changing the current content into a form-xobject will destroy the clip
1844 // objects which is fine since the xobject will already be clipped. However
1845 // if source has shape, we need to clip it too, so a copy of the clip is
1846 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001847
1848 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
1849 SkRegion clipRegion = fContentEntries.front()->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001850
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001851 SkMatrix identity;
1852 identity.reset();
1853 SkPaint stockPaint;
1854
halcanary4b1e17e2016-07-27 14:49:46 -07001855 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001856 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001857 // If nothing was drawn and there's no shape, then the draw was a
1858 // no-op, but dst needs to be restored for that to be true.
1859 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1860 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1861 // reduces to Dst.
halcanary96fcdcc2015-08-27 07:41:13 -07001862 if (shape == nullptr || xfermode == SkXfermode::kDstOut_Mode ||
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001863 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001864 ScopedContentEntry content(this, &fExistingClipStack,
1865 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001866 stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001867 // TODO: addXObjectResource take sk_sp
1868 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001869 &content.entry()->fContent);
1870 return;
1871 } else {
1872 xfermode = SkXfermode::kClear_Mode;
1873 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001874 } else {
halcanary2be7e012016-03-28 11:58:08 -07001875 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001876 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001877 }
1878
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001879 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1880 // without alpha.
1881 if (xfermode == SkXfermode::kSrcATop_Mode) {
1882 // TODO(vandebo): In order to properly support SrcATop we have to track
1883 // the shape of what's been drawn at all times. It's the intersection of
1884 // the non-transparent parts of the device and the outlines (shape) of
1885 // all images and devices drawn.
1886 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001887 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001888 SkXfermode::kSrcOver_Mode, true);
1889 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001890 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001891 // Draw shape into a form-xobject.
reed1e7f5e72016-04-27 07:49:17 -07001892 SkRasterClip rc(clipRegion);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001893 SkDraw d;
1894 d.fMatrix = &identity;
reed1e7f5e72016-04-27 07:49:17 -07001895 d.fRC = &rc;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001896 d.fClipStack = &clipStack;
1897 SkPaint filledPaint;
1898 filledPaint.setColor(SK_ColorBLACK);
1899 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001900 this->drawPath(d, *shape, filledPaint, nullptr, true);
halcanarydabd4f02016-08-03 11:16:56 -07001901 drawFormXObjectWithMask(addXObjectResource(dst.get()),
1902 this->makeFormXObjectFromDevice(),
1903 &fExistingClipStack, fExistingClipRegion,
1904 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001905
halcanarydabd4f02016-08-03 11:16:56 -07001906 } else {
1907 drawFormXObjectWithMask(addXObjectResource(dst.get()), srcFormXObject,
1908 &fExistingClipStack, fExistingClipRegion,
1909 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001910 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001911 }
1912
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001913 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001914 return;
1915 } else if (xfermode == SkXfermode::kSrc_Mode ||
1916 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001917 ScopedContentEntry content(this, &fExistingClipStack,
1918 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001919 if (content.entry()) {
1920 SkPDFUtils::DrawFormXObject(
1921 this->addXObjectResource(srcFormXObject.get()),
1922 &content.entry()->fContent);
1923 }
1924 if (xfermode == SkXfermode::kSrc_Mode) {
1925 return;
1926 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001927 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001928 ScopedContentEntry content(this, &fExistingClipStack,
1929 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001930 if (content.entry()) {
halcanarydabd4f02016-08-03 11:16:56 -07001931 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001932 &content.entry()->fContent);
1933 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001934 }
1935
1936 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1937 xfermode == SkXfermode::kDstIn_Mode ||
1938 xfermode == SkXfermode::kSrcOut_Mode ||
1939 xfermode == SkXfermode::kDstOut_Mode ||
1940 xfermode == SkXfermode::kSrcATop_Mode ||
1941 xfermode == SkXfermode::kDstATop_Mode ||
1942 xfermode == SkXfermode::kModulate_Mode);
1943
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001944 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001945 xfermode == SkXfermode::kSrcOut_Mode ||
1946 xfermode == SkXfermode::kSrcATop_Mode) {
halcanarydabd4f02016-08-03 11:16:56 -07001947 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1948 std::move(dst),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001949 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001950 SkXfermode::kSrcOver_Mode,
1951 xfermode == SkXfermode::kSrcOut_Mode);
halcanarydabd4f02016-08-03 11:16:56 -07001952 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001953 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001954 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
halcanarydabd4f02016-08-03 11:16:56 -07001955 int resourceID = addXObjectResource(dst.get());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001956 if (xfermode == SkXfermode::kModulate_Mode) {
1957 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
halcanarydabd4f02016-08-03 11:16:56 -07001958 std::move(dst), &fExistingClipStack,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001959 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001960 SkXfermode::kSrcOver_Mode, false);
1961 mode = SkXfermode::kMultiply_Mode;
1962 }
halcanarydabd4f02016-08-03 11:16:56 -07001963 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001964 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001965 xfermode == SkXfermode::kDstOut_Mode);
halcanarydabd4f02016-08-03 11:16:56 -07001966 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001967 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001968}
1969
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001970bool SkPDFDevice::isContentEmpty() {
halcanary2be7e012016-03-28 11:58:08 -07001971 if (!fContentEntries.front() || fContentEntries.front()->fContent.getOffset() == 0) {
1972 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001973 return true;
1974 }
1975 return false;
1976}
1977
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001978void SkPDFDevice::populateGraphicStateEntryFromPaint(
1979 const SkMatrix& matrix,
1980 const SkClipStack& clipStack,
1981 const SkRegion& clipRegion,
1982 const SkPaint& paint,
1983 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001984 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001985 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1986 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1987 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001988
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001989 entry->fMatrix = matrix;
1990 entry->fClipStack = clipStack;
1991 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001992 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1993 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001994
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001995 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001996 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001997 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001998 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001999 if (shader) {
2000 // PDF positions patterns relative to the initial transform, so
2001 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002002 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00002003 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002004
2005 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002006 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002007 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00002008
2009 // We need to apply the initial transform to bounds in order to get
2010 // bounds in a consistent coordinate system.
2011 SkRect boundsTemp;
2012 boundsTemp.set(bounds);
2013 fInitialTransform.mapRect(&boundsTemp);
2014 boundsTemp.roundOut(&bounds);
2015
halcanary792c80f2015-02-20 07:21:05 -08002016 SkScalar rasterScale =
2017 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
halcanarydabd4f02016-08-03 11:16:56 -07002018 pdfShader = SkPDFShader::GetPDFShader(
2019 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002020
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002021 if (pdfShader.get()) {
2022 // pdfShader has been canonicalized so we can directly compare
2023 // pointers.
2024 int resourceIndex = fShaderResources.find(pdfShader.get());
2025 if (resourceIndex < 0) {
2026 resourceIndex = fShaderResources.count();
2027 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002028 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002029 }
2030 entry->fShaderIndex = resourceIndex;
2031 } else {
2032 // A color shader is treated as an invalid shader so we don't have
2033 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002034 SkShader::GradientInfo gradientInfo;
2035 SkColor gradientColor;
2036 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002037 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002038 gradientInfo.fColorCount = 1;
2039 if (shader->asAGradient(&gradientInfo) ==
2040 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002041 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2042 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002043 }
2044 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002045 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002046
halcanary48810a02016-03-07 14:57:50 -08002047 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002048 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002049 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002050 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002051 } else {
2052 SkPaint newPaint = paint;
2053 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002054 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002055 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002056 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002057 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002058 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002059
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002060 if (hasText) {
2061 entry->fTextScaleX = paint.getTextScaleX();
2062 entry->fTextFill = paint.getStyle();
2063 } else {
2064 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002065 }
2066}
2067
halcanarybe27a112015-04-01 13:31:19 -07002068int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002069 // Assumes that gs has been canonicalized (so we can directly compare
2070 // pointers).
2071 int result = fGraphicStateResources.find(gs);
2072 if (result < 0) {
2073 result = fGraphicStateResources.count();
2074 fGraphicStateResources.push(gs);
2075 gs->ref();
2076 }
2077 return result;
2078}
2079
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002080int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002081 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002082 // Assumes that xobject has been canonicalized (so we can directly compare
2083 // pointers).
2084 int result = fXObjectResources.find(xObject);
2085 if (result < 0) {
2086 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002087 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002088 }
2089 return result;
2090}
2091
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002092int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08002093 sk_sp<SkPDFFont> newFont(
halcanary989da4a2016-03-21 14:33:17 -07002094 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
halcanary7e8d5d32016-08-12 07:59:38 -07002095 if (!newFont) {
2096 return -1;
2097 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002098 int resourceIndex = fFontResources.find(newFont.get());
2099 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002100 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002101 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002102 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002103 }
2104 return resourceIndex;
2105}
2106
halcanary7a14b312015-10-01 07:28:13 -07002107static SkSize rect_to_size(const SkRect& r) {
2108 return SkSize::Make(r.width(), r.height());
2109}
2110
halcanarya50151d2016-03-25 11:57:49 -07002111static sk_sp<SkImage> color_filter(const SkImageBitmap& imageBitmap,
2112 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002113 auto surface =
halcanarya50151d2016-03-25 11:57:49 -07002114 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageBitmap.dimensions()));
2115 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002116 SkCanvas* canvas = surface->getCanvas();
2117 canvas->clear(SK_ColorTRANSPARENT);
2118 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002119 paint.setColorFilter(sk_ref_sp(colorFilter));
halcanarya50151d2016-03-25 11:57:49 -07002120 imageBitmap.draw(canvas, &paint);
halcanary7a14b312015-10-01 07:28:13 -07002121 canvas->flush();
halcanarya50151d2016-03-25 11:57:49 -07002122 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002123}
2124
2125////////////////////////////////////////////////////////////////////////////////
2126void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2127 const SkClipStack* clipStack,
2128 const SkRegion& origClipRegion,
halcanarya50151d2016-03-25 11:57:49 -07002129 SkImageBitmap imageBitmap,
halcanary7a14b312015-10-01 07:28:13 -07002130 const SkPaint& paint) {
halcanarya50151d2016-03-25 11:57:49 -07002131 if (imageBitmap.dimensions().isZero()) {
2132 return;
2133 }
halcanary7a14b312015-10-01 07:28:13 -07002134 #ifdef SK_PDF_IMAGE_STATS
2135 gDrawImageCalls.fetch_add(1);
2136 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002137 SkMatrix matrix = origMatrix;
2138 SkRegion perspectiveBounds;
2139 const SkRegion* clipRegion = &origClipRegion;
halcanarya50151d2016-03-25 11:57:49 -07002140 sk_sp<SkImage> autoImageUnref;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002141
2142 // Rasterize the bitmap using perspective in a new bitmap.
2143 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002144 if (fRasterDpi == 0) {
2145 return;
2146 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002147 // Transform the bitmap in the new space, without taking into
2148 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002149 SkPath perspectiveOutline;
halcanarya50151d2016-03-25 11:57:49 -07002150 SkRect imageBounds = SkRect::Make(imageBitmap.bounds());
halcanary7a14b312015-10-01 07:28:13 -07002151 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002152 perspectiveOutline.transform(origMatrix);
2153
2154 // TODO(edisonn): perf - use current clip too.
2155 // Retrieve the bounds of the new shape.
2156 SkRect bounds = perspectiveOutline.getBounds();
2157
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002158 // Transform the bitmap in the new space, taking into
2159 // account the initial transform.
2160 SkMatrix total = origMatrix;
2161 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002162 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2163 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2164 total.postScale(dpiScale, dpiScale);
2165
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002166 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002167 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002168 physicalPerspectiveOutline.transform(total);
2169
halcanary7a14b312015-10-01 07:28:13 -07002170 SkRect physicalPerspectiveBounds =
2171 physicalPerspectiveOutline.getBounds();
2172 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2173 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002174
2175 // TODO(edisonn): A better approach would be to use a bitmap shader
2176 // (in clamp mode) and draw a rect over the entire bounding box. Then
2177 // intersect perspectiveOutline to the clip. That will avoid introducing
2178 // alpha to the image while still giving good behavior at the edge of
2179 // the image. Avoiding alpha will reduce the pdf size and generation
2180 // CPU time some.
2181
halcanary7a14b312015-10-01 07:28:13 -07002182 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2183
reede8f30622016-03-23 18:59:25 -07002184 auto surface(SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh)));
halcanary7a14b312015-10-01 07:28:13 -07002185 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002186 return;
2187 }
halcanary7a14b312015-10-01 07:28:13 -07002188 SkCanvas* canvas = surface->getCanvas();
2189 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002190
2191 SkScalar deltaX = bounds.left();
2192 SkScalar deltaY = bounds.top();
2193
2194 SkMatrix offsetMatrix = origMatrix;
2195 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002196 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002197
2198 // Translate the draw in the new canvas, so we perfectly fit the
2199 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002200 canvas->setMatrix(offsetMatrix);
halcanarya50151d2016-03-25 11:57:49 -07002201 imageBitmap.draw(canvas, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002202 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002203 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002204
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002205 // In the new space, we use the identity matrix translated
2206 // and scaled to reflect DPI.
2207 matrix.setScale(1 / scaleX, 1 / scaleY);
2208 matrix.postTranslate(deltaX, deltaY);
2209
halcanary7a14b312015-10-01 07:28:13 -07002210 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002211 clipRegion = &perspectiveBounds;
halcanary7a14b312015-10-01 07:28:13 -07002212
halcanarya50151d2016-03-25 11:57:49 -07002213 autoImageUnref = surface->makeImageSnapshot();
2214 imageBitmap = SkImageBitmap(autoImageUnref.get());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002215 }
2216
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002217 SkMatrix scaled;
2218 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002219 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2220 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002221 // Scale the image up from 1x1 to WxH.
halcanarya50151d2016-03-25 11:57:49 -07002222 SkIRect subset = imageBitmap.bounds();
2223 scaled.postScale(SkIntToScalar(imageBitmap.dimensions().width()),
2224 SkIntToScalar(imageBitmap.dimensions().height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002225 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002226 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002227 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002228 return;
2229 }
2230 if (content.needShape()) {
2231 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002232 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002233 shape.transform(matrix);
2234 content.setShape(shape);
2235 }
2236 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002237 return;
2238 }
2239
halcanary287d22d2015-09-24 10:20:05 -07002240 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002241 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002242 // draw calls. This code here works for all
2243 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2244 // rasterize a layer on this backend). Fortuanely, this seems
2245 // to be how Chromium impements most color-filters.
halcanarya50151d2016-03-25 11:57:49 -07002246 autoImageUnref = color_filter(imageBitmap, colorFilter);
2247 imageBitmap = SkImageBitmap(autoImageUnref.get());
halcanary7a14b312015-10-01 07:28:13 -07002248 // TODO(halcanary): de-dupe this by caching filtered images.
2249 // (maybe in the resource cache?)
2250 }
halcanarya50151d2016-03-25 11:57:49 -07002251
2252 SkBitmapKey key = imageBitmap.getKey();
2253 sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
halcanary7a14b312015-10-01 07:28:13 -07002254 if (!pdfimage) {
halcanary4b1e17e2016-07-27 14:49:46 -07002255 sk_sp<SkImage> img = imageBitmap.makeImage();
halcanarya50151d2016-03-25 11:57:49 -07002256 if (!img) {
2257 return;
2258 }
2259 pdfimage = SkPDFCreateBitmapObject(
2260 std::move(img), fDocument->canon()->getPixelSerializer());
halcanary7a14b312015-10-01 07:28:13 -07002261 if (!pdfimage) {
2262 return;
halcanary287d22d2015-09-24 10:20:05 -07002263 }
halcanarya50151d2016-03-25 11:57:49 -07002264 fDocument->serialize(pdfimage); // serialize images early.
2265 fDocument->canon()->addPDFBitmap(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002266 }
halcanarya50151d2016-03-25 11:57:49 -07002267 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
halcanary3d8c33c2015-10-01 11:06:22 -07002268 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002269 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002270}
reede51c3562016-07-19 14:33:20 -07002271
2272///////////////////////////////////////////////////////////////////////////////////////////////////
2273
2274#include "SkSpecialImage.h"
2275#include "SkImageFilter.h"
2276
2277void SkPDFDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
2278 const SkPaint& paint) {
2279 SkASSERT(!srcImg->isTextureBacked());
2280
2281 SkBitmap resultBM;
2282
2283 SkImageFilter* filter = paint.getImageFilter();
2284 if (filter) {
2285 SkIPoint offset = SkIPoint::Make(0, 0);
2286 SkMatrix matrix = *draw.fMatrix;
2287 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
2288 const SkIRect clipBounds = draw.fRC->getBounds().makeOffset(-x, -y);
2289// SkAutoTUnref<SkImageFilterCache> cache(this->getImageFilterCache());
2290 SkImageFilter::Context ctx(matrix, clipBounds, nullptr /*cache.get()*/);
2291
2292 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2293 if (resultImg) {
2294 SkPaint tmpUnfiltered(paint);
2295 tmpUnfiltered.setImageFilter(nullptr);
2296 if (resultImg->getROPixels(&resultBM)) {
2297 this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2298 }
2299 }
2300 } else {
2301 if (srcImg->getROPixels(&resultBM)) {
2302 this->drawSprite(draw, resultBM, x, y, paint);
2303 }
2304 }
2305}
2306
2307sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2308 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2309}
2310
2311sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
2312 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
2313 image->makeNonTextureImage());
2314}
2315
2316sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002317 return nullptr;
2318}