• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkTypes.h"
9 #if defined(SK_BUILD_FOR_WIN)
10 
11 #include "src/base/SkLeanWindows.h"
12 
13 #ifndef UNICODE
14 #define UNICODE
15 #endif
16 #ifndef _UNICODE
17 #define _UNICODE
18 #endif
19 #include <ObjBase.h>
20 #include <XpsObjectModel.h>
21 #include <T2EmbApi.h>
22 #include <FontSub.h>
23 #include <limits>
24 
25 #include "include/core/SkColor.h"
26 #include "include/core/SkData.h"
27 #include "include/core/SkEncodedImageFormat.h"
28 #include "include/core/SkImage.h"
29 #include "include/core/SkImageEncoder.h"
30 #include "include/core/SkPaint.h"
31 #include "include/core/SkPathEffect.h"
32 #include "include/core/SkPathUtils.h"
33 #include "include/core/SkPoint.h"
34 #include "include/core/SkShader.h"
35 #include "include/core/SkSize.h"
36 #include "include/core/SkStream.h"
37 #include "include/core/SkVertices.h"
38 #include "include/pathops/SkPathOps.h"
39 #include "include/private/base/SkTDArray.h"
40 #include "include/private/base/SkTo.h"
41 #include "src/base/SkTLazy.h"
42 #include "src/base/SkUtils.h"
43 #include "src/core/SkDraw.h"
44 #include "src/core/SkEndian.h"
45 #include "src/core/SkGeometry.h"
46 #include "src/core/SkImagePriv.h"
47 #include "src/core/SkMaskFilterBase.h"
48 #include "src/core/SkRasterClip.h"
49 #include "src/core/SkStrikeCache.h"
50 #include "src/image/SkImage_Base.h"
51 #include "src/sfnt/SkSFNTHeader.h"
52 #include "src/sfnt/SkTTCFHeader.h"
53 #include "src/shaders/SkShaderBase.h"
54 #include "src/text/GlyphRun.h"
55 #include "src/utils/SkClipStackUtils.h"
56 #include "src/utils/win/SkHRESULT.h"
57 #include "src/utils/win/SkIStream.h"
58 #include "src/utils/win/SkTScopedComPtr.h"
59 #include "src/xps/SkXPSDevice.h"
60 
61 using namespace skia_private;
62 
63 //Windows defines a FLOAT type,
64 //make it clear when converting a scalar that this is what is wanted.
65 #define SkScalarToFLOAT(n) SkScalarToFloat(n)
66 
67 //Placeholder representation of a GUID from createId.
68 #define L_GUID_ID L"XXXXXXXXsXXXXsXXXXsXXXXsXXXXXXXXXXXX"
69 //Length of GUID representation from createId, including nullptr terminator.
70 #define GUID_ID_LEN std::size(L_GUID_ID)
71 
72 /**
73    Formats a GUID and places it into buffer.
74    buffer should have space for at least GUID_ID_LEN wide characters.
75    The string will always be wchar null terminated.
76    XXXXXXXXsXXXXsXXXXsXXXXsXXXXXXXXXXXX0
77    @return -1 if there was an error, > 0 if success.
78  */
format_guid(const GUID & guid,wchar_t * buffer,size_t bufferSize,wchar_t sep='-')79 static int format_guid(const GUID& guid,
80                        wchar_t* buffer, size_t bufferSize,
81                        wchar_t sep = '-') {
82     SkASSERT(bufferSize >= GUID_ID_LEN);
83     return swprintf_s(buffer,
84                       bufferSize,
85                       L"%08lX%c%04X%c%04X%c%02X%02X%c%02X%02X%02X%02X%02X%02X",
86                       guid.Data1,
87                       sep,
88                       guid.Data2,
89                       sep,
90                       guid.Data3,
91                       sep,
92                       guid.Data4[0],
93                       guid.Data4[1],
94                       sep,
95                       guid.Data4[2],
96                       guid.Data4[3],
97                       guid.Data4[4],
98                       guid.Data4[5],
99                       guid.Data4[6],
100                       guid.Data4[7]);
101 }
102 
createId(wchar_t * buffer,size_t bufferSize,wchar_t sep)103 HRESULT SkXPSDevice::createId(wchar_t* buffer, size_t bufferSize, wchar_t sep) {
104     GUID guid = {};
105 #ifdef SK_XPS_USE_DETERMINISTIC_IDS
106     guid.Data1 = fNextId++;
107     // The following make this a valid Type4 UUID.
108     guid.Data3 = 0x4000;
109     guid.Data4[0] = 0x80;
110 #else
111     HRM(CoCreateGuid(&guid), "Could not create GUID for id.");
112 #endif
113 
114     if (format_guid(guid, buffer, bufferSize, sep) == -1) {
115         HRM(E_UNEXPECTED, "Could not format GUID into id.");
116     }
117 
118     return S_OK;
119 }
120 
SkXPSDevice(SkISize s)121 SkXPSDevice::SkXPSDevice(SkISize s)
122     : INHERITED(SkImageInfo::MakeUnknown(s.width(), s.height()),
123                 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
124     , fCurrentPage(0), fTopTypefaces(&fTypefaces) {}
125 
~SkXPSDevice()126 SkXPSDevice::~SkXPSDevice() {}
127 
beginPortfolio(SkWStream * outputStream,IXpsOMObjectFactory * factory)128 bool SkXPSDevice::beginPortfolio(SkWStream* outputStream, IXpsOMObjectFactory* factory) {
129     SkASSERT(factory);
130     fXpsFactory.reset(SkRefComPtr(factory));
131     HRB(SkWIStream::CreateFromSkWStream(outputStream, &this->fOutputStream));
132     return true;
133 }
134 
beginSheet(const SkVector & unitsPerMeter,const SkVector & pixelsPerMeter,const SkSize & trimSize,const SkRect * mediaBox,const SkRect * bleedBox,const SkRect * artBox,const SkRect * cropBox)135 bool SkXPSDevice::beginSheet(
136         const SkVector& unitsPerMeter,
137         const SkVector& pixelsPerMeter,
138         const SkSize& trimSize,
139         const SkRect* mediaBox,
140         const SkRect* bleedBox,
141         const SkRect* artBox,
142         const SkRect* cropBox) {
143     ++this->fCurrentPage;
144 
145     //For simplicity, just write everything out in geometry units,
146     //then have a base canvas do the scale to physical units.
147     this->fCurrentCanvasSize = trimSize;
148     this->fCurrentUnitsPerMeter = unitsPerMeter;
149     this->fCurrentPixelsPerMeter = pixelsPerMeter;
150     return this->createCanvasForLayer();
151 }
152 
createCanvasForLayer()153 bool SkXPSDevice::createCanvasForLayer() {
154     SkASSERT(fXpsFactory);
155     fCurrentXpsCanvas.reset();
156     HRB(fXpsFactory->CreateCanvas(&fCurrentXpsCanvas));
157     return true;
158 }
159 
sk_digits_in()160 template <typename T> static constexpr size_t sk_digits_in() {
161     return static_cast<size_t>(std::numeric_limits<T>::digits10 + 1);
162 }
163 
createXpsThumbnail(IXpsOMPage * page,const unsigned int pageNum,IXpsOMImageResource ** image)164 HRESULT SkXPSDevice::createXpsThumbnail(IXpsOMPage* page,
165                                         const unsigned int pageNum,
166                                         IXpsOMImageResource** image) {
167     SkTScopedComPtr<IXpsOMThumbnailGenerator> thumbnailGenerator;
168     HRM(CoCreateInstance(
169             CLSID_XpsOMThumbnailGenerator,
170             nullptr,
171             CLSCTX_INPROC_SERVER,
172             IID_PPV_ARGS(&thumbnailGenerator)),
173         "Could not create thumbnail generator.");
174 
175     SkTScopedComPtr<IOpcPartUri> partUri;
176     constexpr size_t size = std::max(
177             std::size(L"/Documents/1/Metadata/.png") + sk_digits_in<decltype(pageNum)>(),
178             std::size(L"/Metadata/" L_GUID_ID L".png"));
179     wchar_t buffer[size];
180     if (pageNum > 0) {
181         swprintf_s(buffer, size, L"/Documents/1/Metadata/%u.png", pageNum);
182     } else {
183         wchar_t id[GUID_ID_LEN];
184         HR(this->createId(id, GUID_ID_LEN));
185         swprintf_s(buffer, size, L"/Metadata/%s.png", id);
186     }
187     HRM(this->fXpsFactory->CreatePartUri(buffer, &partUri),
188         "Could not create thumbnail part uri.");
189 
190     HRM(thumbnailGenerator->GenerateThumbnail(page,
191                                               XPS_IMAGE_TYPE_PNG,
192                                               XPS_THUMBNAIL_SIZE_LARGE,
193                                               partUri.get(),
194                                               image),
195         "Could not generate thumbnail.");
196 
197     return S_OK;
198 }
199 
createXpsPage(const XPS_SIZE & pageSize,IXpsOMPage ** page)200 HRESULT SkXPSDevice::createXpsPage(const XPS_SIZE& pageSize,
201                                    IXpsOMPage** page) {
202     constexpr size_t size =
203         std::size(L"/Documents/1/Pages/.fpage")
204         + sk_digits_in<decltype(fCurrentPage)>();
205     wchar_t buffer[size];
206     swprintf_s(buffer, size, L"/Documents/1/Pages/%u.fpage",
207                              this->fCurrentPage);
208     SkTScopedComPtr<IOpcPartUri> partUri;
209     HRM(this->fXpsFactory->CreatePartUri(buffer, &partUri),
210         "Could not create page part uri.");
211 
212     //If the language is unknown, use "und" (XPS Spec 2.3.5.1).
213     HRM(this->fXpsFactory->CreatePage(&pageSize,
214                                       L"und",
215                                       partUri.get(),
216                                       page),
217         "Could not create page.");
218 
219     return S_OK;
220 }
221 
initXpsDocumentWriter(IXpsOMImageResource * image)222 HRESULT SkXPSDevice::initXpsDocumentWriter(IXpsOMImageResource* image) {
223     //Create package writer.
224     {
225         SkTScopedComPtr<IOpcPartUri> partUri;
226         HRM(this->fXpsFactory->CreatePartUri(L"/FixedDocumentSequence.fdseq",
227                                              &partUri),
228             "Could not create document sequence part uri.");
229         HRM(this->fXpsFactory->CreatePackageWriterOnStream(
230                 this->fOutputStream.get(),
231                 TRUE,
232                 XPS_INTERLEAVING_OFF, //XPS_INTERLEAVING_ON,
233                 partUri.get(),
234                 nullptr,
235                 image,
236                 nullptr,
237                 nullptr,
238                 &this->fPackageWriter),
239             "Could not create package writer.");
240     }
241 
242     //Begin the lone document.
243     {
244         SkTScopedComPtr<IOpcPartUri> partUri;
245         HRM(this->fXpsFactory->CreatePartUri(
246                 L"/Documents/1/FixedDocument.fdoc",
247                 &partUri),
248             "Could not create fixed document part uri.");
249         HRM(this->fPackageWriter->StartNewDocument(partUri.get(),
250                                                    nullptr,
251                                                    nullptr,
252                                                    nullptr,
253                                                    nullptr),
254             "Could not start document.");
255     }
256 
257     return S_OK;
258 }
259 
endSheet()260 bool SkXPSDevice::endSheet() {
261     //XPS is fixed at 96dpi (XPS Spec 11.1).
262     static const float xpsDPI = 96.0f;
263     static const float inchesPerMeter = 10000.0f / 254.0f;
264     static const float targetUnitsPerMeter = xpsDPI * inchesPerMeter;
265     const float scaleX = targetUnitsPerMeter
266                        / SkScalarToFLOAT(this->fCurrentUnitsPerMeter.fX);
267     const float scaleY = targetUnitsPerMeter
268                        / SkScalarToFLOAT(this->fCurrentUnitsPerMeter.fY);
269 
270     //Create the scale canvas.
271     SkTScopedComPtr<IXpsOMCanvas> scaleCanvas;
272     HRBM(this->fXpsFactory->CreateCanvas(&scaleCanvas),
273          "Could not create scale canvas.");
274     SkTScopedComPtr<IXpsOMVisualCollection> scaleCanvasVisuals;
275     HRBM(scaleCanvas->GetVisuals(&scaleCanvasVisuals),
276          "Could not get scale canvas visuals.");
277 
278     SkTScopedComPtr<IXpsOMMatrixTransform> geomToPhys;
279     XPS_MATRIX rawGeomToPhys = { scaleX, 0, 0, scaleY, 0, 0, };
280     HRBM(this->fXpsFactory->CreateMatrixTransform(&rawGeomToPhys, &geomToPhys),
281          "Could not create geometry to physical transform.");
282     HRBM(scaleCanvas->SetTransformLocal(geomToPhys.get()),
283          "Could not set transform on scale canvas.");
284 
285     //Add the content canvas to the scale canvas.
286     HRBM(scaleCanvasVisuals->Append(this->fCurrentXpsCanvas.get()),
287          "Could not add base canvas to scale canvas.");
288 
289     //Create the page.
290     XPS_SIZE pageSize = {
291         SkScalarToFLOAT(this->fCurrentCanvasSize.width()) * scaleX,
292         SkScalarToFLOAT(this->fCurrentCanvasSize.height()) * scaleY,
293     };
294     SkTScopedComPtr<IXpsOMPage> page;
295     HRB(this->createXpsPage(pageSize, &page));
296 
297     SkTScopedComPtr<IXpsOMVisualCollection> pageVisuals;
298     HRBM(page->GetVisuals(&pageVisuals), "Could not get page visuals.");
299 
300     //Add the scale canvas to the page.
301     HRBM(pageVisuals->Append(scaleCanvas.get()),
302          "Could not add scale canvas to page.");
303 
304     //Create the package writer if it hasn't been created yet.
305     if (nullptr == this->fPackageWriter.get()) {
306         SkTScopedComPtr<IXpsOMImageResource> image;
307         //Ignore return, thumbnail is completely optional.
308         this->createXpsThumbnail(page.get(), 0, &image);
309 
310         HRB(this->initXpsDocumentWriter(image.get()));
311     }
312 
313     HRBM(this->fPackageWriter->AddPage(page.get(),
314                                        &pageSize,
315                                        nullptr,
316                                        nullptr,
317                                        nullptr,
318                                        nullptr),
319          "Could not write the page.");
320     this->fCurrentXpsCanvas.reset();
321 
322     return true;
323 }
324 
subset_typeface(const SkXPSDevice::TypefaceUse & current)325 static HRESULT subset_typeface(const SkXPSDevice::TypefaceUse& current) {
326     //The CreateFontPackage API is only supported on desktop, not in UWP
327     #if defined(SK_WINUWP)
328     return E_NOTIMPL;
329     #else
330     //CreateFontPackage wants unsigned short.
331     //Microsoft, Y U NO stdint.h?
332     std::vector<unsigned short> keepList;
333     current.glyphsUsed.forEachSetIndex([&keepList](size_t v) {
334             keepList.push_back((unsigned short)v);
335     });
336 
337     int ttcCount = (current.ttcIndex + 1);
338 
339     //The following are declared with the types required by CreateFontPackage.
340     unsigned char *fontPackageBufferRaw = nullptr;
341     unsigned long fontPackageBufferSize;
342     unsigned long bytesWritten;
343     unsigned long result = CreateFontPackage(
344         (unsigned char *) current.fontData->getMemoryBase(),
345         (unsigned long) current.fontData->getLength(),
346         &fontPackageBufferRaw,
347         &fontPackageBufferSize,
348         &bytesWritten,
349         TTFCFP_FLAGS_SUBSET | TTFCFP_FLAGS_GLYPHLIST | (ttcCount > 0 ? TTFCFP_FLAGS_TTC : 0),
350         current.ttcIndex,
351         TTFCFP_SUBSET,
352         0,
353         0,
354         0,
355         keepList.data(),
356         SkTo<unsigned short>(keepList.size()),
357         sk_malloc_throw,
358         sk_realloc_throw,
359         sk_free,
360         nullptr);
361     AutoTMalloc<unsigned char> fontPackageBuffer(fontPackageBufferRaw);
362     if (result != NO_ERROR) {
363         SkDEBUGF("CreateFontPackage Error %lu", result);
364         return E_UNEXPECTED;
365     }
366 
367     // If it was originally a ttc, keep it a ttc.
368     // CreateFontPackage over-allocates, realloc usually decreases the size substantially.
369     size_t extra;
370     if (ttcCount > 0) {
371         // Create space for a ttc header.
372         extra = sizeof(SkTTCFHeader) + (ttcCount * sizeof(SK_OT_ULONG));
373         fontPackageBuffer.realloc(bytesWritten + extra);
374         //overlap is certain, use memmove
375         memmove(fontPackageBuffer.get() + extra, fontPackageBuffer.get(), bytesWritten);
376 
377         // Write the ttc header.
378         SkTTCFHeader* ttcfHeader = reinterpret_cast<SkTTCFHeader*>(fontPackageBuffer.get());
379         ttcfHeader->ttcTag = SkTTCFHeader::TAG;
380         ttcfHeader->version = SkTTCFHeader::version_1;
381         ttcfHeader->numOffsets = SkEndian_SwapBE32(ttcCount);
382         SK_OT_ULONG* offsetPtr = SkTAfter<SK_OT_ULONG>(ttcfHeader);
383         for (int i = 0; i < ttcCount; ++i, ++offsetPtr) {
384             *offsetPtr = SkEndian_SwapBE32(SkToU32(extra));
385         }
386 
387         // Fix up offsets in sfnt table entries.
388         SkSFNTHeader* sfntHeader = SkTAddOffset<SkSFNTHeader>(fontPackageBuffer.get(), extra);
389         int numTables = SkEndian_SwapBE16(sfntHeader->numTables);
390         SkSFNTHeader::TableDirectoryEntry* tableDirectory =
391             SkTAfter<SkSFNTHeader::TableDirectoryEntry>(sfntHeader);
392         for (int i = 0; i < numTables; ++i, ++tableDirectory) {
393             tableDirectory->offset = SkEndian_SwapBE32(
394                 SkToU32(SkEndian_SwapBE32(SkToU32(tableDirectory->offset)) + extra));
395         }
396     } else {
397         extra = 0;
398         fontPackageBuffer.realloc(bytesWritten);
399     }
400 
401     std::unique_ptr<SkMemoryStream> newStream(new SkMemoryStream());
402     newStream->setMemoryOwned(fontPackageBuffer.release(), bytesWritten + extra);
403 
404     SkTScopedComPtr<IStream> newIStream;
405     SkIStream::CreateFromSkStream(std::move(newStream), &newIStream);
406 
407     XPS_FONT_EMBEDDING embedding;
408     HRM(current.xpsFont->GetEmbeddingOption(&embedding),
409         "Could not get embedding option from font.");
410 
411     SkTScopedComPtr<IOpcPartUri> partUri;
412     HRM(current.xpsFont->GetPartName(&partUri),
413         "Could not get part uri from font.");
414 
415     HRM(current.xpsFont->SetContent(
416             newIStream.get(),
417             embedding,
418             partUri.get()),
419         "Could not set new stream for subsetted font.");
420 
421     return S_OK;
422     #endif //SK_WINUWP
423 }
424 
endPortfolio()425 bool SkXPSDevice::endPortfolio() {
426     //Subset fonts
427     for (const TypefaceUse& current : *this->fTopTypefaces) {
428         //Ignore return for now, if it didn't subset, let it be.
429         subset_typeface(current);
430     }
431 
432     if (this->fPackageWriter) {
433         HRBM(this->fPackageWriter->Close(), "Could not close writer.");
434     }
435 
436     return true;
437 }
438 
xps_color(const SkColor skColor)439 static XPS_COLOR xps_color(const SkColor skColor) {
440     //XPS uses non-pre-multiplied alpha (XPS Spec 11.4).
441     XPS_COLOR xpsColor;
442     xpsColor.colorType = XPS_COLOR_TYPE_SRGB;
443     xpsColor.value.sRGB.alpha = SkColorGetA(skColor);
444     xpsColor.value.sRGB.red = SkColorGetR(skColor);
445     xpsColor.value.sRGB.green = SkColorGetG(skColor);
446     xpsColor.value.sRGB.blue = SkColorGetB(skColor);
447 
448     return xpsColor;
449 }
450 
xps_point(const SkPoint & point)451 static XPS_POINT xps_point(const SkPoint& point) {
452     XPS_POINT xpsPoint = {
453         SkScalarToFLOAT(point.fX),
454         SkScalarToFLOAT(point.fY),
455     };
456     return xpsPoint;
457 }
458 
xps_point(const SkPoint & point,const SkMatrix & matrix)459 static XPS_POINT xps_point(const SkPoint& point, const SkMatrix& matrix) {
460     SkPoint skTransformedPoint;
461     matrix.mapXY(point.fX, point.fY, &skTransformedPoint);
462     return xps_point(skTransformedPoint);
463 }
464 
xps_spread_method(SkTileMode tileMode)465 static XPS_SPREAD_METHOD xps_spread_method(SkTileMode tileMode) {
466     switch (tileMode) {
467     case SkTileMode::kClamp:
468         return XPS_SPREAD_METHOD_PAD;
469     case SkTileMode::kRepeat:
470         return XPS_SPREAD_METHOD_REPEAT;
471     case SkTileMode::kMirror:
472         return XPS_SPREAD_METHOD_REFLECT;
473     case SkTileMode::kDecal:
474         // TODO: fake
475         return XPS_SPREAD_METHOD_PAD;
476     default:
477         SkDEBUGFAIL("Unknown tile mode.");
478     }
479     return XPS_SPREAD_METHOD_PAD;
480 }
481 
transform_offsets(SkScalar * stopOffsets,const int numOffsets,const SkPoint & start,const SkPoint & end,const SkMatrix & transform)482 static void transform_offsets(SkScalar* stopOffsets, const int numOffsets,
483                               const SkPoint& start, const SkPoint& end,
484                               const SkMatrix& transform) {
485     SkPoint startTransformed;
486     transform.mapXY(start.fX, start.fY, &startTransformed);
487     SkPoint endTransformed;
488     transform.mapXY(end.fX, end.fY, &endTransformed);
489 
490     //Manhattan distance between transformed start and end.
491     SkScalar startToEnd = (endTransformed.fX - startTransformed.fX)
492                         + (endTransformed.fY - startTransformed.fY);
493     if (SkScalarNearlyZero(startToEnd)) {
494         for (int i = 0; i < numOffsets; ++i) {
495             stopOffsets[i] = 0;
496         }
497         return;
498     }
499 
500     for (int i = 0; i < numOffsets; ++i) {
501         SkPoint stop;
502         stop.fX = (end.fX - start.fX) * stopOffsets[i];
503         stop.fY = (end.fY - start.fY) * stopOffsets[i];
504 
505         SkPoint stopTransformed;
506         transform.mapXY(stop.fX, stop.fY, &stopTransformed);
507 
508         //Manhattan distance between transformed start and stop.
509         SkScalar startToStop = (stopTransformed.fX - startTransformed.fX)
510                              + (stopTransformed.fY - startTransformed.fY);
511         //Percentage along transformed line.
512         stopOffsets[i] = startToStop / startToEnd;
513     }
514 }
515 
createXpsTransform(const SkMatrix & matrix,IXpsOMMatrixTransform ** xpsTransform)516 HRESULT SkXPSDevice::createXpsTransform(const SkMatrix& matrix,
517                                         IXpsOMMatrixTransform** xpsTransform) {
518     SkScalar affine[6];
519     if (!matrix.asAffine(affine)) {
520         *xpsTransform = nullptr;
521         return S_FALSE;
522     }
523     XPS_MATRIX rawXpsMatrix = {
524         SkScalarToFLOAT(affine[SkMatrix::kAScaleX]),
525         SkScalarToFLOAT(affine[SkMatrix::kASkewY]),
526         SkScalarToFLOAT(affine[SkMatrix::kASkewX]),
527         SkScalarToFLOAT(affine[SkMatrix::kAScaleY]),
528         SkScalarToFLOAT(affine[SkMatrix::kATransX]),
529         SkScalarToFLOAT(affine[SkMatrix::kATransY]),
530     };
531     HRM(this->fXpsFactory->CreateMatrixTransform(&rawXpsMatrix, xpsTransform),
532         "Could not create transform.");
533 
534     return S_OK;
535 }
536 
createPath(IXpsOMGeometryFigure * figure,IXpsOMVisualCollection * visuals,IXpsOMPath ** path)537 HRESULT SkXPSDevice::createPath(IXpsOMGeometryFigure* figure,
538                                 IXpsOMVisualCollection* visuals,
539                                 IXpsOMPath** path) {
540     SkTScopedComPtr<IXpsOMGeometry> geometry;
541     HRM(this->fXpsFactory->CreateGeometry(&geometry),
542         "Could not create geometry.");
543 
544     SkTScopedComPtr<IXpsOMGeometryFigureCollection> figureCollection;
545     HRM(geometry->GetFigures(&figureCollection), "Could not get figures.");
546     HRM(figureCollection->Append(figure), "Could not add figure.");
547 
548     HRM(this->fXpsFactory->CreatePath(path), "Could not create path.");
549     HRM((*path)->SetGeometryLocal(geometry.get()), "Could not set geometry");
550 
551     HRM(visuals->Append(*path), "Could not add path to visuals.");
552     return S_OK;
553 }
554 
createXpsSolidColorBrush(const SkColor skColor,const SkAlpha alpha,IXpsOMBrush ** xpsBrush)555 HRESULT SkXPSDevice::createXpsSolidColorBrush(const SkColor skColor,
556                                               const SkAlpha alpha,
557                                               IXpsOMBrush** xpsBrush) {
558     XPS_COLOR xpsColor = xps_color(skColor);
559     SkTScopedComPtr<IXpsOMSolidColorBrush> solidBrush;
560     HRM(this->fXpsFactory->CreateSolidColorBrush(&xpsColor, nullptr, &solidBrush),
561         "Could not create solid color brush.");
562     HRM(solidBrush->SetOpacity(alpha / 255.0f), "Could not set opacity.");
563     HRM(solidBrush->QueryInterface<IXpsOMBrush>(xpsBrush), "QI Fail.");
564     return S_OK;
565 }
566 
sideOfClamp(const SkRect & areaToFill,const XPS_RECT & imageViewBox,IXpsOMImageResource * image,IXpsOMVisualCollection * visuals)567 HRESULT SkXPSDevice::sideOfClamp(const SkRect& areaToFill,
568                                  const XPS_RECT& imageViewBox,
569                                  IXpsOMImageResource* image,
570                                  IXpsOMVisualCollection* visuals) {
571     SkTScopedComPtr<IXpsOMGeometryFigure> areaToFillFigure;
572     HR(this->createXpsRect(areaToFill, FALSE, TRUE, &areaToFillFigure));
573 
574     SkTScopedComPtr<IXpsOMPath> areaToFillPath;
575     HR(this->createPath(areaToFillFigure.get(), visuals, &areaToFillPath));
576 
577     SkTScopedComPtr<IXpsOMImageBrush> areaToFillBrush;
578     HRM(this->fXpsFactory->CreateImageBrush(image,
579                                             &imageViewBox,
580                                             &imageViewBox,
581                                             &areaToFillBrush),
582         "Could not create brush for side of clamp.");
583     HRM(areaToFillBrush->SetTileMode(XPS_TILE_MODE_FLIPXY),
584         "Could not set tile mode for side of clamp.");
585     HRM(areaToFillPath->SetFillBrushLocal(areaToFillBrush.get()),
586         "Could not set brush for side of clamp");
587 
588     return S_OK;
589 }
590 
cornerOfClamp(const SkRect & areaToFill,const SkColor color,IXpsOMVisualCollection * visuals)591 HRESULT SkXPSDevice::cornerOfClamp(const SkRect& areaToFill,
592                                    const SkColor color,
593                                    IXpsOMVisualCollection* visuals) {
594     SkTScopedComPtr<IXpsOMGeometryFigure> areaToFillFigure;
595     HR(this->createXpsRect(areaToFill, FALSE, TRUE, &areaToFillFigure));
596 
597     SkTScopedComPtr<IXpsOMPath> areaToFillPath;
598     HR(this->createPath(areaToFillFigure.get(), visuals, &areaToFillPath));
599 
600     SkTScopedComPtr<IXpsOMBrush> areaToFillBrush;
601     HR(this->createXpsSolidColorBrush(color, 0xFF, &areaToFillBrush));
602     HRM(areaToFillPath->SetFillBrushLocal(areaToFillBrush.get()),
603         "Could not set brush for corner of clamp.");
604 
605     return S_OK;
606 }
607 
608 static const XPS_TILE_MODE XTM_N  = XPS_TILE_MODE_NONE;
609 static const XPS_TILE_MODE XTM_T  = XPS_TILE_MODE_TILE;
610 static const XPS_TILE_MODE XTM_X  = XPS_TILE_MODE_FLIPX;
611 static const XPS_TILE_MODE XTM_Y  = XPS_TILE_MODE_FLIPY;
612 static const XPS_TILE_MODE XTM_XY = XPS_TILE_MODE_FLIPXY;
613 
614 //TODO(bungeman): In the future, should skia add None,
615 //handle None+Mirror and None+Repeat correctly.
616 //None is currently an internal hack so masks don't repeat (None+None only).
617 static XPS_TILE_MODE gSkToXpsTileMode[kSkTileModeCount+1]
618                                      [kSkTileModeCount+1] = {
619                //Clamp  //Repeat //Mirror //None
620     /*Clamp */ {XTM_N,  XTM_T,   XTM_Y,   XTM_N},
621     /*Repeat*/ {XTM_T,  XTM_T,   XTM_Y,   XTM_N},
622     /*Mirror*/ {XTM_X,  XTM_X,   XTM_XY,  XTM_X},
623     /*None  */ {XTM_N,  XTM_N,   XTM_Y,   XTM_N},
624 };
625 
SkToXpsTileMode(SkTileMode tmx,SkTileMode tmy)626 static XPS_TILE_MODE SkToXpsTileMode(SkTileMode tmx, SkTileMode tmy) {
627     return gSkToXpsTileMode[(unsigned)tmx][(unsigned)tmy];
628 }
629 
createXpsImageBrush(const SkBitmap & bitmap,const SkMatrix & localMatrix,const SkTileMode (& xy)[2],const SkAlpha alpha,IXpsOMTileBrush ** xpsBrush)630 HRESULT SkXPSDevice::createXpsImageBrush(
631         const SkBitmap& bitmap,
632         const SkMatrix& localMatrix,
633         const SkTileMode (&xy)[2],
634         const SkAlpha alpha,
635         IXpsOMTileBrush** xpsBrush) {
636     SkDynamicMemoryWStream write;
637     if (!SkEncodeImage(&write, bitmap, SkEncodedImageFormat::kPNG, 100)) {
638         HRM(E_FAIL, "Unable to encode bitmap as png.");
639     }
640     SkTScopedComPtr<IStream> read;
641     HRM(SkIStream::CreateFromSkStream(write.detachAsStream(), &read),
642         "Could not create stream from png data.");
643 
644     const size_t size =
645         std::size(L"/Documents/1/Resources/Images/" L_GUID_ID L".png");
646     wchar_t buffer[size];
647     wchar_t id[GUID_ID_LEN];
648     HR(this->createId(id, GUID_ID_LEN));
649     swprintf_s(buffer, size, L"/Documents/1/Resources/Images/%s.png", id);
650 
651     SkTScopedComPtr<IOpcPartUri> imagePartUri;
652     HRM(this->fXpsFactory->CreatePartUri(buffer, &imagePartUri),
653         "Could not create image part uri.");
654 
655     SkTScopedComPtr<IXpsOMImageResource> imageResource;
656     HRM(this->fXpsFactory->CreateImageResource(
657             read.get(),
658             XPS_IMAGE_TYPE_PNG,
659             imagePartUri.get(),
660             &imageResource),
661         "Could not create image resource.");
662 
663     XPS_RECT bitmapRect = {
664         0.0, 0.0,
665         static_cast<FLOAT>(bitmap.width()), static_cast<FLOAT>(bitmap.height())
666     };
667     SkTScopedComPtr<IXpsOMImageBrush> xpsImageBrush;
668     HRM(this->fXpsFactory->CreateImageBrush(imageResource.get(),
669                                             &bitmapRect, &bitmapRect,
670                                             &xpsImageBrush),
671         "Could not create image brush.");
672 
673     if (SkTileMode::kClamp != xy[0] &&
674         SkTileMode::kClamp != xy[1]) {
675 
676         HRM(xpsImageBrush->SetTileMode(SkToXpsTileMode(xy[0], xy[1])),
677             "Could not set image tile mode");
678         HRM(xpsImageBrush->SetOpacity(alpha / 255.0f),
679             "Could not set image opacity.");
680         HRM(xpsImageBrush->QueryInterface(xpsBrush), "QI failed.");
681     } else {
682         //TODO(bungeman): compute how big this really needs to be.
683         const SkScalar BIG = SkIntToScalar(1000); //SK_ScalarMax;
684         const FLOAT BIG_F = SkScalarToFLOAT(BIG);
685         const SkScalar bWidth = SkIntToScalar(bitmap.width());
686         const SkScalar bHeight = SkIntToScalar(bitmap.height());
687 
688         //create brush canvas
689         SkTScopedComPtr<IXpsOMCanvas> brushCanvas;
690         HRM(this->fXpsFactory->CreateCanvas(&brushCanvas),
691             "Could not create image brush canvas.");
692         SkTScopedComPtr<IXpsOMVisualCollection> brushVisuals;
693         HRM(brushCanvas->GetVisuals(&brushVisuals),
694             "Could not get image brush canvas visuals collection.");
695 
696         //create central figure
697         const SkRect bitmapPoints = SkRect::MakeLTRB(0, 0, bWidth, bHeight);
698         SkTScopedComPtr<IXpsOMGeometryFigure> centralFigure;
699         HR(this->createXpsRect(bitmapPoints, FALSE, TRUE, &centralFigure));
700 
701         SkTScopedComPtr<IXpsOMPath> centralPath;
702         HR(this->createPath(centralFigure.get(),
703                             brushVisuals.get(),
704                             &centralPath));
705         HRM(xpsImageBrush->SetTileMode(XPS_TILE_MODE_FLIPXY),
706             "Could not set tile mode for image brush central path.");
707         HRM(centralPath->SetFillBrushLocal(xpsImageBrush.get()),
708             "Could not set fill brush for image brush central path.");
709 
710         //add left/right
711         if (SkTileMode::kClamp == xy[0]) {
712             SkRect leftArea = SkRect::MakeLTRB(-BIG, 0, 0, bHeight);
713             XPS_RECT leftImageViewBox = {
714                 0.0, 0.0,
715                 1.0, static_cast<FLOAT>(bitmap.height()),
716             };
717             HR(this->sideOfClamp(leftArea, leftImageViewBox,
718                                  imageResource.get(),
719                                  brushVisuals.get()));
720 
721             SkRect rightArea = SkRect::MakeLTRB(bWidth, 0, BIG, bHeight);
722             XPS_RECT rightImageViewBox = {
723                 bitmap.width() - 1.0f, 0.0f,
724                 1.0f, static_cast<FLOAT>(bitmap.height()),
725             };
726             HR(this->sideOfClamp(rightArea, rightImageViewBox,
727                                  imageResource.get(),
728                                  brushVisuals.get()));
729         }
730 
731         //add top/bottom
732         if (SkTileMode::kClamp == xy[1]) {
733             SkRect topArea = SkRect::MakeLTRB(0, -BIG, bWidth, 0);
734             XPS_RECT topImageViewBox = {
735                 0.0, 0.0,
736                 static_cast<FLOAT>(bitmap.width()), 1.0,
737             };
738             HR(this->sideOfClamp(topArea, topImageViewBox,
739                                  imageResource.get(),
740                                  brushVisuals.get()));
741 
742             SkRect bottomArea = SkRect::MakeLTRB(0, bHeight, bWidth, BIG);
743             XPS_RECT bottomImageViewBox = {
744                 0.0f, bitmap.height() - 1.0f,
745                 static_cast<FLOAT>(bitmap.width()), 1.0f,
746             };
747             HR(this->sideOfClamp(bottomArea, bottomImageViewBox,
748                                  imageResource.get(),
749                                  brushVisuals.get()));
750         }
751 
752         //add tl, tr, bl, br
753         if (SkTileMode::kClamp == xy[0] &&
754             SkTileMode::kClamp == xy[1]) {
755 
756             const SkColor tlColor = bitmap.getColor(0,0);
757             const SkRect tlArea = SkRect::MakeLTRB(-BIG, -BIG, 0, 0);
758             HR(this->cornerOfClamp(tlArea, tlColor, brushVisuals.get()));
759 
760             const SkColor trColor = bitmap.getColor(bitmap.width()-1,0);
761             const SkRect trArea = SkRect::MakeLTRB(bWidth, -BIG, BIG, 0);
762             HR(this->cornerOfClamp(trArea, trColor, brushVisuals.get()));
763 
764             const SkColor brColor = bitmap.getColor(bitmap.width()-1,
765                                                     bitmap.height()-1);
766             const SkRect brArea = SkRect::MakeLTRB(bWidth, bHeight, BIG, BIG);
767             HR(this->cornerOfClamp(brArea, brColor, brushVisuals.get()));
768 
769             const SkColor blColor = bitmap.getColor(0,bitmap.height()-1);
770             const SkRect blArea = SkRect::MakeLTRB(-BIG, bHeight, 0, BIG);
771             HR(this->cornerOfClamp(blArea, blColor, brushVisuals.get()));
772         }
773 
774         //create visual brush from canvas
775         XPS_RECT bound = {};
776         if (SkTileMode::kClamp == xy[0] &&
777             SkTileMode::kClamp == xy[1]) {
778 
779             bound.x = BIG_F / -2;
780             bound.y = BIG_F / -2;
781             bound.width = BIG_F;
782             bound.height = BIG_F;
783         } else if (SkTileMode::kClamp == xy[0]) {
784             bound.x = BIG_F / -2;
785             bound.y = 0.0f;
786             bound.width = BIG_F;
787             bound.height = static_cast<FLOAT>(bitmap.height());
788         } else if (SkTileMode::kClamp == xy[1]) {
789             bound.x = 0;
790             bound.y = BIG_F / -2;
791             bound.width = static_cast<FLOAT>(bitmap.width());
792             bound.height = BIG_F;
793         }
794         SkTScopedComPtr<IXpsOMVisualBrush> clampBrush;
795         HRM(this->fXpsFactory->CreateVisualBrush(&bound, &bound, &clampBrush),
796             "Could not create visual brush for image brush.");
797         HRM(clampBrush->SetVisualLocal(brushCanvas.get()),
798             "Could not set canvas on visual brush for image brush.");
799         HRM(clampBrush->SetTileMode(SkToXpsTileMode(xy[0], xy[1])),
800             "Could not set tile mode on visual brush for image brush.");
801         HRM(clampBrush->SetOpacity(alpha / 255.0f),
802             "Could not set opacity on visual brush for image brush.");
803 
804         HRM(clampBrush->QueryInterface(xpsBrush), "QI failed.");
805     }
806 
807     SkTScopedComPtr<IXpsOMMatrixTransform> xpsMatrixToUse;
808     HR(this->createXpsTransform(localMatrix, &xpsMatrixToUse));
809     if (xpsMatrixToUse.get()) {
810         HRM((*xpsBrush)->SetTransformLocal(xpsMatrixToUse.get()),
811             "Could not set transform for image brush.");
812     } else {
813         //TODO(bungeman): perspective bitmaps in general.
814     }
815 
816     return S_OK;
817 }
818 
createXpsGradientStop(const SkColor skColor,const SkScalar offset,IXpsOMGradientStop ** xpsGradStop)819 HRESULT SkXPSDevice::createXpsGradientStop(const SkColor skColor,
820                                            const SkScalar offset,
821                                            IXpsOMGradientStop** xpsGradStop) {
822     XPS_COLOR gradStopXpsColor = xps_color(skColor);
823     HRM(this->fXpsFactory->CreateGradientStop(&gradStopXpsColor,
824                                               nullptr,
825                                               SkScalarToFLOAT(offset),
826                                               xpsGradStop),
827         "Could not create gradient stop.");
828     return S_OK;
829 }
830 
createXpsLinearGradient(SkShaderBase::GradientInfo info,const SkAlpha alpha,const SkMatrix & localMatrix,IXpsOMMatrixTransform * xpsMatrix,IXpsOMBrush ** xpsBrush)831 HRESULT SkXPSDevice::createXpsLinearGradient(SkShaderBase::GradientInfo info,
832                                              const SkAlpha alpha,
833                                              const SkMatrix& localMatrix,
834                                              IXpsOMMatrixTransform* xpsMatrix,
835                                              IXpsOMBrush** xpsBrush) {
836     XPS_POINT startPoint;
837     XPS_POINT endPoint;
838     if (xpsMatrix) {
839         startPoint = xps_point(info.fPoint[0]);
840         endPoint = xps_point(info.fPoint[1]);
841     } else {
842         transform_offsets(info.fColorOffsets, info.fColorCount,
843                           info.fPoint[0], info.fPoint[1],
844                           localMatrix);
845         startPoint = xps_point(info.fPoint[0], localMatrix);
846         endPoint = xps_point(info.fPoint[1], localMatrix);
847     }
848 
849     SkTScopedComPtr<IXpsOMGradientStop> gradStop0;
850     HR(createXpsGradientStop(info.fColors[0],
851                              info.fColorOffsets[0],
852                              &gradStop0));
853 
854     SkTScopedComPtr<IXpsOMGradientStop> gradStop1;
855     HR(createXpsGradientStop(info.fColors[1],
856                              info.fColorOffsets[1],
857                              &gradStop1));
858 
859     SkTScopedComPtr<IXpsOMLinearGradientBrush> gradientBrush;
860     HRM(this->fXpsFactory->CreateLinearGradientBrush(gradStop0.get(),
861                                                      gradStop1.get(),
862                                                      &startPoint,
863                                                      &endPoint,
864                                                      &gradientBrush),
865         "Could not create linear gradient brush.");
866     if (xpsMatrix) {
867         HRM(gradientBrush->SetTransformLocal(xpsMatrix),
868             "Could not set transform on linear gradient brush.");
869     }
870 
871     SkTScopedComPtr<IXpsOMGradientStopCollection> gradStopCollection;
872     HRM(gradientBrush->GetGradientStops(&gradStopCollection),
873         "Could not get linear gradient stop collection.");
874     for (int i = 2; i < info.fColorCount; ++i) {
875         SkTScopedComPtr<IXpsOMGradientStop> gradStop;
876         HR(createXpsGradientStop(info.fColors[i],
877                                  info.fColorOffsets[i],
878                                  &gradStop));
879         HRM(gradStopCollection->Append(gradStop.get()),
880             "Could not add linear gradient stop.");
881     }
882 
883     HRM(gradientBrush->SetSpreadMethod(xps_spread_method((SkTileMode)info.fTileMode)),
884         "Could not set spread method of linear gradient.");
885 
886     HRM(gradientBrush->SetOpacity(alpha / 255.0f),
887         "Could not set opacity of linear gradient brush.");
888     HRM(gradientBrush->QueryInterface<IXpsOMBrush>(xpsBrush), "QI failed");
889 
890     return S_OK;
891 }
892 
createXpsRadialGradient(SkShaderBase::GradientInfo info,const SkAlpha alpha,const SkMatrix & localMatrix,IXpsOMMatrixTransform * xpsMatrix,IXpsOMBrush ** xpsBrush)893 HRESULT SkXPSDevice::createXpsRadialGradient(SkShaderBase::GradientInfo info,
894                                              const SkAlpha alpha,
895                                              const SkMatrix& localMatrix,
896                                              IXpsOMMatrixTransform* xpsMatrix,
897                                              IXpsOMBrush** xpsBrush) {
898     SkTScopedComPtr<IXpsOMGradientStop> gradStop0;
899     HR(createXpsGradientStop(info.fColors[0],
900                              info.fColorOffsets[0],
901                              &gradStop0));
902 
903     SkTScopedComPtr<IXpsOMGradientStop> gradStop1;
904     HR(createXpsGradientStop(info.fColors[1],
905                              info.fColorOffsets[1],
906                              &gradStop1));
907 
908     //TODO: figure out how to fake better if not affine
909     XPS_POINT centerPoint;
910     XPS_POINT gradientOrigin;
911     XPS_SIZE radiiSizes;
912     if (xpsMatrix) {
913         centerPoint = xps_point(info.fPoint[0]);
914         gradientOrigin = xps_point(info.fPoint[0]);
915         radiiSizes.width = SkScalarToFLOAT(info.fRadius[0]);
916         radiiSizes.height = SkScalarToFLOAT(info.fRadius[0]);
917     } else {
918         centerPoint = xps_point(info.fPoint[0], localMatrix);
919         gradientOrigin = xps_point(info.fPoint[0], localMatrix);
920 
921         SkScalar radius = info.fRadius[0];
922         SkVector vec[2];
923 
924         vec[0].set(radius, 0);
925         vec[1].set(0, radius);
926         localMatrix.mapVectors(vec, 2);
927 
928         SkScalar d0 = vec[0].length();
929         SkScalar d1 = vec[1].length();
930 
931         radiiSizes.width = SkScalarToFLOAT(d0);
932         radiiSizes.height = SkScalarToFLOAT(d1);
933     }
934 
935     SkTScopedComPtr<IXpsOMRadialGradientBrush> gradientBrush;
936     HRM(this->fXpsFactory->CreateRadialGradientBrush(gradStop0.get(),
937                                                      gradStop1.get(),
938                                                      &centerPoint,
939                                                      &gradientOrigin,
940                                                      &radiiSizes,
941                                                      &gradientBrush),
942         "Could not create radial gradient brush.");
943     if (xpsMatrix) {
944         HRM(gradientBrush->SetTransformLocal(xpsMatrix),
945             "Could not set transform on radial gradient brush.");
946     }
947 
948     SkTScopedComPtr<IXpsOMGradientStopCollection> gradStopCollection;
949     HRM(gradientBrush->GetGradientStops(&gradStopCollection),
950         "Could not get radial gradient stop collection.");
951     for (int i = 2; i < info.fColorCount; ++i) {
952         SkTScopedComPtr<IXpsOMGradientStop> gradStop;
953         HR(createXpsGradientStop(info.fColors[i],
954                                  info.fColorOffsets[i],
955                                  &gradStop));
956         HRM(gradStopCollection->Append(gradStop.get()),
957             "Could not add radial gradient stop.");
958     }
959 
960     HRM(gradientBrush->SetSpreadMethod(xps_spread_method((SkTileMode)info.fTileMode)),
961         "Could not set spread method of radial gradient.");
962 
963     HRM(gradientBrush->SetOpacity(alpha / 255.0f),
964         "Could not set opacity of radial gradient brush.");
965     HRM(gradientBrush->QueryInterface<IXpsOMBrush>(xpsBrush), "QI failed.");
966 
967     return S_OK;
968 }
969 
createXpsBrush(const SkPaint & skPaint,IXpsOMBrush ** brush,const SkMatrix * parentTransform)970 HRESULT SkXPSDevice::createXpsBrush(const SkPaint& skPaint,
971                                     IXpsOMBrush** brush,
972                                     const SkMatrix* parentTransform) {
973     const SkShader *shader = skPaint.getShader();
974     if (nullptr == shader) {
975         HR(this->createXpsSolidColorBrush(skPaint.getColor(), 0xFF, brush));
976         return S_OK;
977     }
978 
979     //Gradient shaders.
980     SkShaderBase::GradientInfo info;
981     SkShaderBase::GradientType gradientType = as_SB(shader)->asGradient(&info);
982 
983     if (gradientType == SkShaderBase::GradientType::kNone) {
984         //Nothing to see, move along.
985 
986     } else if (gradientType == SkShaderBase::GradientType::kColor) {
987         SkASSERT(1 == info.fColorCount);
988         SkColor color;
989         info.fColors = &color;
990         as_SB(shader)->asGradient(&info);
991         SkAlpha alpha = skPaint.getAlpha();
992         HR(this->createXpsSolidColorBrush(color, alpha, brush));
993         return S_OK;
994 
995     } else {
996         if (info.fColorCount == 0) {
997             const SkColor color = skPaint.getColor();
998             HR(this->createXpsSolidColorBrush(color, 0xFF, brush));
999             return S_OK;
1000         }
1001 
1002         SkMatrix localMatrix;
1003         AutoTArray<SkColor> colors(info.fColorCount);
1004         AutoTArray<SkScalar> colorOffsets(info.fColorCount);
1005         info.fColors = colors.get();
1006         info.fColorOffsets = colorOffsets.get();
1007         as_SB(shader)->asGradient(&info, &localMatrix);
1008 
1009         if (1 == info.fColorCount) {
1010             SkColor color = info.fColors[0];
1011             SkAlpha alpha = skPaint.getAlpha();
1012             HR(this->createXpsSolidColorBrush(color, alpha, brush));
1013             return S_OK;
1014         }
1015 
1016         if (parentTransform) {
1017             localMatrix.preConcat(*parentTransform);
1018         }
1019         SkTScopedComPtr<IXpsOMMatrixTransform> xpsMatrixToUse;
1020         HR(this->createXpsTransform(localMatrix, &xpsMatrixToUse));
1021 
1022         if (gradientType == SkShaderBase::GradientType::kLinear) {
1023             HR(this->createXpsLinearGradient(info,
1024                                              skPaint.getAlpha(),
1025                                              localMatrix,
1026                                              xpsMatrixToUse.get(),
1027                                              brush));
1028             return S_OK;
1029         }
1030 
1031         if (gradientType == SkShaderBase::GradientType::kRadial) {
1032             HR(this->createXpsRadialGradient(info,
1033                                              skPaint.getAlpha(),
1034                                              localMatrix,
1035                                              xpsMatrixToUse.get(),
1036                                              brush));
1037             return S_OK;
1038         }
1039 
1040         if (gradientType == SkShaderBase::GradientType::kConical) {
1041             //simple if affine and one is 0, otherwise will have to fake
1042         }
1043 
1044         if (gradientType == SkShaderBase::GradientType::kSweep) {
1045             //have to fake
1046         }
1047     }
1048 
1049     SkBitmap outTexture;
1050     SkMatrix outMatrix;
1051     SkTileMode xy[2];
1052     SkImage* image = shader->isAImage(&outMatrix, xy);
1053     if (image->asLegacyBitmap(&outTexture)) {
1054         if (parentTransform) {
1055             outMatrix.postConcat(*parentTransform);
1056         }
1057 
1058         SkTScopedComPtr<IXpsOMTileBrush> tileBrush;
1059         HR(this->createXpsImageBrush(outTexture, outMatrix, xy, skPaint.getAlpha(), &tileBrush));
1060 
1061         HRM(tileBrush->QueryInterface<IXpsOMBrush>(brush), "QI failed.");
1062     } else {
1063         HR(this->createXpsSolidColorBrush(skPaint.getColor(), 0xFF, brush));
1064     }
1065     return S_OK;
1066 }
1067 
rect_must_be_pathed(const SkPaint & paint,const SkMatrix & matrix)1068 static bool rect_must_be_pathed(const SkPaint& paint, const SkMatrix& matrix) {
1069     const bool zeroWidth = (0 == paint.getStrokeWidth());
1070     const bool stroke = (SkPaint::kFill_Style != paint.getStyle());
1071 
1072     return paint.getPathEffect() ||
1073            paint.getMaskFilter() ||
1074            (stroke && (
1075                (matrix.hasPerspective() && !zeroWidth) ||
1076                SkPaint::kMiter_Join != paint.getStrokeJoin() ||
1077                (SkPaint::kMiter_Join == paint.getStrokeJoin() &&
1078                 paint.getStrokeMiter() < SK_ScalarSqrt2)
1079            ))
1080     ;
1081 }
1082 
createXpsRect(const SkRect & rect,BOOL stroke,BOOL fill,IXpsOMGeometryFigure ** xpsRect)1083 HRESULT SkXPSDevice::createXpsRect(const SkRect& rect, BOOL stroke, BOOL fill,
1084                                    IXpsOMGeometryFigure** xpsRect) {
1085     const SkPoint points[4] = {
1086         { rect.fLeft, rect.fTop },
1087         { rect.fRight, rect.fTop },
1088         { rect.fRight, rect.fBottom },
1089         { rect.fLeft, rect.fBottom },
1090     };
1091     return this->createXpsQuad(points, stroke, fill, xpsRect);
1092 }
createXpsQuad(const SkPoint (& points)[4],BOOL stroke,BOOL fill,IXpsOMGeometryFigure ** xpsQuad)1093 HRESULT SkXPSDevice::createXpsQuad(const SkPoint (&points)[4],
1094                                    BOOL stroke, BOOL fill,
1095                                    IXpsOMGeometryFigure** xpsQuad) {
1096     // Define the start point.
1097     XPS_POINT startPoint = xps_point(points[0]);
1098 
1099     // Create the figure.
1100     HRM(this->fXpsFactory->CreateGeometryFigure(&startPoint, xpsQuad),
1101         "Could not create quad geometry figure.");
1102 
1103     // Define the type of each segment.
1104     XPS_SEGMENT_TYPE segmentTypes[3] = {
1105         XPS_SEGMENT_TYPE_LINE,
1106         XPS_SEGMENT_TYPE_LINE,
1107         XPS_SEGMENT_TYPE_LINE,
1108     };
1109 
1110     // Define the x and y coordinates of each corner of the figure.
1111     FLOAT segmentData[6] = {
1112         SkScalarToFLOAT(points[1].fX), SkScalarToFLOAT(points[1].fY),
1113         SkScalarToFLOAT(points[2].fX), SkScalarToFLOAT(points[2].fY),
1114         SkScalarToFLOAT(points[3].fX), SkScalarToFLOAT(points[3].fY),
1115     };
1116 
1117     // Describe if the segments are stroked.
1118     BOOL segmentStrokes[3] = {
1119         stroke, stroke, stroke,
1120     };
1121 
1122     // Add the segment data to the figure.
1123     HRM((*xpsQuad)->SetSegments(
1124             3, 6,
1125             segmentTypes , segmentData, segmentStrokes),
1126         "Could not add segment data to quad.");
1127 
1128     // Set the closed and filled properties of the figure.
1129     HRM((*xpsQuad)->SetIsClosed(stroke), "Could not set quad close.");
1130     HRM((*xpsQuad)->SetIsFilled(fill), "Could not set quad fill.");
1131 
1132     return S_OK;
1133 }
1134 
drawPoints(SkCanvas::PointMode mode,size_t count,const SkPoint points[],const SkPaint & paint)1135 void SkXPSDevice::drawPoints(SkCanvas::PointMode mode,
1136                              size_t count, const SkPoint points[],
1137                              const SkPaint& paint) {
1138     //TODO
1139 }
1140 
drawVertices(const SkVertices *,sk_sp<SkBlender>,const SkPaint &,bool)1141 void SkXPSDevice::drawVertices(const SkVertices*, sk_sp<SkBlender>, const SkPaint&, bool) {
1142     //TODO
1143 }
1144 
drawMesh(const SkMesh &,sk_sp<SkBlender>,const SkPaint &)1145 void SkXPSDevice::drawMesh(const SkMesh&, sk_sp<SkBlender>, const SkPaint&) {
1146     // TODO
1147 }
1148 
drawPaint(const SkPaint & origPaint)1149 void SkXPSDevice::drawPaint(const SkPaint& origPaint) {
1150     const SkRect r = SkRect::MakeSize(this->fCurrentCanvasSize);
1151 
1152     //If trying to paint with a stroke, ignore that and fill.
1153     SkPaint* fillPaint = const_cast<SkPaint*>(&origPaint);
1154     SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
1155     if (paint->getStyle() != SkPaint::kFill_Style) {
1156         paint.writable()->setStyle(SkPaint::kFill_Style);
1157     }
1158 
1159     this->internalDrawRect(r, false, *fillPaint);
1160 }
1161 
drawRect(const SkRect & r,const SkPaint & paint)1162 void SkXPSDevice::drawRect(const SkRect& r,
1163                            const SkPaint& paint) {
1164     this->internalDrawRect(r, true, paint);
1165 }
1166 
drawRRect(const SkRRect & rr,const SkPaint & paint)1167 void SkXPSDevice::drawRRect(const SkRRect& rr,
1168                             const SkPaint& paint) {
1169     SkPath path;
1170     path.addRRect(rr);
1171     this->drawPath(path, paint, true);
1172 }
1173 
size(const SkBaseDevice & dev)1174 static SkIRect size(const SkBaseDevice& dev) { return {0, 0, dev.width(), dev.height()}; }
1175 
internalDrawRect(const SkRect & r,bool transformRect,const SkPaint & paint)1176 void SkXPSDevice::internalDrawRect(const SkRect& r,
1177                                    bool transformRect,
1178                                    const SkPaint& paint) {
1179     //Exit early if there is nothing to draw.
1180     if (this->cs().isEmpty(size(*this)) ||
1181         (paint.getAlpha() == 0 && paint.isSrcOver())) {
1182         return;
1183     }
1184 
1185     //Path the rect if we can't optimize it.
1186     if (rect_must_be_pathed(paint, this->localToDevice())) {
1187         SkPath tmp;
1188         tmp.addRect(r);
1189         tmp.setFillType(SkPathFillType::kWinding);
1190         this->drawPath(tmp, paint, true);
1191         return;
1192     }
1193 
1194     //Create the shaded path.
1195     SkTScopedComPtr<IXpsOMPath> shadedPath;
1196     HRVM(this->fXpsFactory->CreatePath(&shadedPath),
1197          "Could not create shaded path for rect.");
1198 
1199     //Create the shaded geometry.
1200     SkTScopedComPtr<IXpsOMGeometry> shadedGeometry;
1201     HRVM(this->fXpsFactory->CreateGeometry(&shadedGeometry),
1202          "Could not create shaded geometry for rect.");
1203 
1204     //Add the geometry to the shaded path.
1205     HRVM(shadedPath->SetGeometryLocal(shadedGeometry.get()),
1206          "Could not set shaded geometry for rect.");
1207 
1208     //Set the brushes.
1209     BOOL fill = FALSE;
1210     BOOL stroke = FALSE;
1211     HRV(this->shadePath(shadedPath.get(), paint, this->localToDevice(), &fill, &stroke));
1212 
1213     bool xpsTransformsPath = true;
1214     //Transform the geometry.
1215     if (transformRect && xpsTransformsPath) {
1216         SkTScopedComPtr<IXpsOMMatrixTransform> xpsTransform;
1217         HRV(this->createXpsTransform(this->localToDevice(), &xpsTransform));
1218         if (xpsTransform.get()) {
1219             HRVM(shadedGeometry->SetTransformLocal(xpsTransform.get()),
1220                  "Could not set transform for rect.");
1221         } else {
1222             xpsTransformsPath = false;
1223         }
1224     }
1225 
1226     //Create the figure.
1227     SkTScopedComPtr<IXpsOMGeometryFigure> rectFigure;
1228     {
1229         SkPoint points[4] = {
1230             { r.fLeft, r.fTop },
1231             { r.fLeft, r.fBottom },
1232             { r.fRight, r.fBottom },
1233             { r.fRight, r.fTop },
1234         };
1235         if (!xpsTransformsPath && transformRect) {
1236             this->localToDevice().mapPoints(points, std::size(points));
1237         }
1238         HRV(this->createXpsQuad(points, stroke, fill, &rectFigure));
1239     }
1240 
1241     //Get the figures of the shaded geometry.
1242     SkTScopedComPtr<IXpsOMGeometryFigureCollection> shadedFigures;
1243     HRVM(shadedGeometry->GetFigures(&shadedFigures),
1244          "Could not get shaded figures for rect.");
1245 
1246     //Add the figure to the shaded geometry figures.
1247     HRVM(shadedFigures->Append(rectFigure.get()),
1248          "Could not add shaded figure for rect.");
1249 
1250     HRV(this->clip(shadedPath.get()));
1251 
1252     //Add the shaded path to the current visuals.
1253     SkTScopedComPtr<IXpsOMVisualCollection> currentVisuals;
1254     HRVM(this->fCurrentXpsCanvas->GetVisuals(&currentVisuals),
1255          "Could not get current visuals for rect.");
1256     HRVM(currentVisuals->Append(shadedPath.get()),
1257          "Could not add rect to current visuals.");
1258 }
1259 
close_figure(const SkTDArray<XPS_SEGMENT_TYPE> & segmentTypes,const SkTDArray<FLOAT> & segmentData,const SkTDArray<BOOL> & segmentStrokes,BOOL stroke,BOOL fill,IXpsOMGeometryFigure * figure,IXpsOMGeometryFigureCollection * figures)1260 static HRESULT close_figure(const SkTDArray<XPS_SEGMENT_TYPE>& segmentTypes,
1261                             const SkTDArray<FLOAT>& segmentData,
1262                             const SkTDArray<BOOL>& segmentStrokes,
1263                             BOOL stroke, BOOL fill,
1264                             IXpsOMGeometryFigure* figure,
1265                             IXpsOMGeometryFigureCollection* figures) {
1266     // Either all are empty or none are empty.
1267     SkASSERT(( segmentTypes.empty() &&  segmentData.empty() &&  segmentStrokes.empty()) ||
1268              (!segmentTypes.empty() && !segmentData.empty() && !segmentStrokes.empty()));
1269 
1270     // SkTDArray::begin() may return nullptr when the segment is empty,
1271     // but IXpsOMGeometryFigure::SetSegments returns E_POINTER if any of the pointers are nullptr
1272     // even if the counts are all 0.
1273     if (!segmentTypes.empty() && !segmentData.empty() && !segmentStrokes.empty()) {
1274         // Add the segment data to the figure.
1275         HRM(figure->SetSegments(segmentTypes.size(), segmentData.size(),
1276                                 segmentTypes.begin(), segmentData.begin(), segmentStrokes.begin()),
1277             "Could not set path segments.");
1278     }
1279 
1280     // Set the closed and filled properties of the figure.
1281     HRM(figure->SetIsClosed(stroke), "Could not set path closed.");
1282     HRM(figure->SetIsFilled(fill), "Could not set path fill.");
1283 
1284     // Add the figure created above to this geometry.
1285     HRM(figures->Append(figure), "Could not add path to geometry.");
1286     return S_OK;
1287 }
1288 
addXpsPathGeometry(IXpsOMGeometryFigureCollection * xpsFigures,BOOL stroke,BOOL fill,const SkPath & path)1289 HRESULT SkXPSDevice::addXpsPathGeometry(
1290         IXpsOMGeometryFigureCollection* xpsFigures,
1291         BOOL stroke, BOOL fill, const SkPath& path) {
1292     SkTDArray<XPS_SEGMENT_TYPE> segmentTypes;
1293     SkTDArray<FLOAT> segmentData;
1294     SkTDArray<BOOL> segmentStrokes;
1295 
1296     SkTScopedComPtr<IXpsOMGeometryFigure> xpsFigure;
1297     SkPath::Iter iter(path, true);
1298     SkPoint points[4];
1299     SkPath::Verb verb;
1300     while ((verb = iter.next(points)) != SkPath::kDone_Verb) {
1301         switch (verb) {
1302             case SkPath::kMove_Verb: {
1303                 if (xpsFigure.get()) {
1304                     HR(close_figure(segmentTypes, segmentData, segmentStrokes,
1305                                     stroke, fill,
1306                                     xpsFigure.get() , xpsFigures));
1307                     segmentTypes.clear();
1308                     segmentData.clear();
1309                     segmentStrokes.clear();
1310                     xpsFigure.reset();
1311                 }
1312                 // Define the start point.
1313                 XPS_POINT startPoint = xps_point(points[0]);
1314                 // Create the figure.
1315                 HRM(this->fXpsFactory->CreateGeometryFigure(&startPoint,
1316                                                             &xpsFigure),
1317                     "Could not create path geometry figure.");
1318                 break;
1319             }
1320             case SkPath::kLine_Verb:
1321                 if (iter.isCloseLine()) break; //ignore the line, auto-closed
1322                 segmentTypes.push_back(XPS_SEGMENT_TYPE_LINE);
1323                 segmentData.push_back(SkScalarToFLOAT(points[1].fX));
1324                 segmentData.push_back(SkScalarToFLOAT(points[1].fY));
1325                 segmentStrokes.push_back(stroke);
1326                 break;
1327             case SkPath::kQuad_Verb:
1328                 segmentTypes.push_back(XPS_SEGMENT_TYPE_QUADRATIC_BEZIER);
1329                 segmentData.push_back(SkScalarToFLOAT(points[1].fX));
1330                 segmentData.push_back(SkScalarToFLOAT(points[1].fY));
1331                 segmentData.push_back(SkScalarToFLOAT(points[2].fX));
1332                 segmentData.push_back(SkScalarToFLOAT(points[2].fY));
1333                 segmentStrokes.push_back(stroke);
1334                 break;
1335             case SkPath::kCubic_Verb:
1336                 segmentTypes.push_back(XPS_SEGMENT_TYPE_BEZIER);
1337                 segmentData.push_back(SkScalarToFLOAT(points[1].fX));
1338                 segmentData.push_back(SkScalarToFLOAT(points[1].fY));
1339                 segmentData.push_back(SkScalarToFLOAT(points[2].fX));
1340                 segmentData.push_back(SkScalarToFLOAT(points[2].fY));
1341                 segmentData.push_back(SkScalarToFLOAT(points[3].fX));
1342                 segmentData.push_back(SkScalarToFLOAT(points[3].fY));
1343                 segmentStrokes.push_back(stroke);
1344                 break;
1345             case SkPath::kConic_Verb: {
1346                 const SkScalar tol = SK_Scalar1 / 4;
1347                 SkAutoConicToQuads converter;
1348                 const SkPoint* quads =
1349                     converter.computeQuads(points, iter.conicWeight(), tol);
1350                 for (int i = 0; i < converter.countQuads(); ++i) {
1351                     segmentTypes.push_back(XPS_SEGMENT_TYPE_QUADRATIC_BEZIER);
1352                     segmentData.push_back(SkScalarToFLOAT(quads[2 * i + 1].fX));
1353                     segmentData.push_back(SkScalarToFLOAT(quads[2 * i + 1].fY));
1354                     segmentData.push_back(SkScalarToFLOAT(quads[2 * i + 2].fX));
1355                     segmentData.push_back(SkScalarToFLOAT(quads[2 * i + 2].fY));
1356                     segmentStrokes.push_back(stroke);
1357                 }
1358                 break;
1359             }
1360             case SkPath::kClose_Verb:
1361                 // we ignore these, and just get the whole segment from
1362                 // the corresponding line/quad/cubic verbs
1363                 break;
1364             default:
1365                 SkDEBUGFAIL("unexpected verb");
1366                 break;
1367         }
1368     }
1369     if (xpsFigure.get()) {
1370         HR(close_figure(segmentTypes, segmentData, segmentStrokes,
1371                         stroke, fill,
1372                         xpsFigure.get(), xpsFigures));
1373     }
1374     return S_OK;
1375 }
1376 
convertToPpm(const SkMaskFilter * filter,SkMatrix * matrix,SkVector * ppuScale,const SkIRect & clip,SkIRect * clipIRect)1377 void SkXPSDevice::convertToPpm(const SkMaskFilter* filter,
1378                                SkMatrix* matrix,
1379                                SkVector* ppuScale,
1380                                const SkIRect& clip, SkIRect* clipIRect) {
1381     //This action is in unit space, but the ppm is specified in physical space.
1382     ppuScale->set(fCurrentPixelsPerMeter.fX / fCurrentUnitsPerMeter.fX,
1383                   fCurrentPixelsPerMeter.fY / fCurrentUnitsPerMeter.fY);
1384 
1385     matrix->postScale(ppuScale->fX, ppuScale->fY);
1386 
1387     const SkIRect& irect = clip;
1388     SkRect clipRect = SkRect::MakeLTRB(SkIntToScalar(irect.fLeft) * ppuScale->fX,
1389                                        SkIntToScalar(irect.fTop) * ppuScale->fY,
1390                                        SkIntToScalar(irect.fRight) * ppuScale->fX,
1391                                        SkIntToScalar(irect.fBottom) * ppuScale->fY);
1392     clipRect.roundOut(clipIRect);
1393 }
1394 
applyMask(const SkMask & mask,const SkVector & ppuScale,IXpsOMPath * shadedPath)1395 HRESULT SkXPSDevice::applyMask(const SkMask& mask,
1396                                const SkVector& ppuScale,
1397                                IXpsOMPath* shadedPath) {
1398     //Get the geometry object.
1399     SkTScopedComPtr<IXpsOMGeometry> shadedGeometry;
1400     HRM(shadedPath->GetGeometry(&shadedGeometry),
1401         "Could not get mask shaded geometry.");
1402 
1403     //Get the figures from the geometry.
1404     SkTScopedComPtr<IXpsOMGeometryFigureCollection> shadedFigures;
1405     HRM(shadedGeometry->GetFigures(&shadedFigures),
1406         "Could not get mask shaded figures.");
1407 
1408     SkMatrix m;
1409     m.reset();
1410     m.setTranslate(SkIntToScalar(mask.fBounds.fLeft),
1411                    SkIntToScalar(mask.fBounds.fTop));
1412     m.postScale(SkScalarInvert(ppuScale.fX), SkScalarInvert(ppuScale.fY));
1413 
1414     SkTileMode xy[2];
1415     xy[0] = (SkTileMode)3;
1416     xy[1] = (SkTileMode)3;
1417 
1418     SkBitmap bm;
1419     bm.installMaskPixels(mask);
1420 
1421     SkTScopedComPtr<IXpsOMTileBrush> maskBrush;
1422     HR(this->createXpsImageBrush(bm, m, xy, 0xFF, &maskBrush));
1423     HRM(shadedPath->SetOpacityMaskBrushLocal(maskBrush.get()),
1424         "Could not set mask.");
1425 
1426     const SkRect universeRect = SkRect::MakeLTRB(0, 0,
1427         this->fCurrentCanvasSize.fWidth, this->fCurrentCanvasSize.fHeight);
1428     SkTScopedComPtr<IXpsOMGeometryFigure> shadedFigure;
1429     HRM(this->createXpsRect(universeRect, FALSE, TRUE, &shadedFigure),
1430         "Could not create mask shaded figure.");
1431     HRM(shadedFigures->Append(shadedFigure.get()),
1432         "Could not add mask shaded figure.");
1433 
1434     HR(this->clip(shadedPath));
1435 
1436     //Add the path to the active visual collection.
1437     SkTScopedComPtr<IXpsOMVisualCollection> currentVisuals;
1438     HRM(this->fCurrentXpsCanvas->GetVisuals(&currentVisuals),
1439         "Could not get mask current visuals.");
1440     HRM(currentVisuals->Append(shadedPath),
1441         "Could not add masked shaded path to current visuals.");
1442 
1443     return S_OK;
1444 }
1445 
shadePath(IXpsOMPath * shadedPath,const SkPaint & shaderPaint,const SkMatrix & matrix,BOOL * fill,BOOL * stroke)1446 HRESULT SkXPSDevice::shadePath(IXpsOMPath* shadedPath,
1447                                const SkPaint& shaderPaint,
1448                                const SkMatrix& matrix,
1449                                BOOL* fill, BOOL* stroke) {
1450     *fill = FALSE;
1451     *stroke = FALSE;
1452 
1453     const SkPaint::Style style = shaderPaint.getStyle();
1454     const bool hasFill = SkPaint::kFill_Style == style
1455                       || SkPaint::kStrokeAndFill_Style == style;
1456     const bool hasStroke = SkPaint::kStroke_Style == style
1457                         || SkPaint::kStrokeAndFill_Style == style;
1458 
1459     //TODO(bungeman): use dictionaries and lookups.
1460     if (hasFill) {
1461         *fill = TRUE;
1462         SkTScopedComPtr<IXpsOMBrush> fillBrush;
1463         HR(this->createXpsBrush(shaderPaint, &fillBrush, &matrix));
1464         HRM(shadedPath->SetFillBrushLocal(fillBrush.get()),
1465             "Could not set fill for shaded path.");
1466     }
1467 
1468     if (hasStroke) {
1469         *stroke = TRUE;
1470         SkTScopedComPtr<IXpsOMBrush> strokeBrush;
1471         HR(this->createXpsBrush(shaderPaint, &strokeBrush, &matrix));
1472         HRM(shadedPath->SetStrokeBrushLocal(strokeBrush.get()),
1473             "Could not set stroke brush for shaded path.");
1474         HRM(shadedPath->SetStrokeThickness(
1475                 SkScalarToFLOAT(shaderPaint.getStrokeWidth())),
1476             "Could not set shaded path stroke thickness.");
1477 
1478         if (0 == shaderPaint.getStrokeWidth()) {
1479             //XPS hair width is a hack. (XPS Spec 11.6.12).
1480             SkTScopedComPtr<IXpsOMDashCollection> dashes;
1481             HRM(shadedPath->GetStrokeDashes(&dashes),
1482                 "Could not set dashes for shaded path.");
1483             XPS_DASH dash;
1484             dash.length = 1.0;
1485             dash.gap = 0.0;
1486             HRM(dashes->Append(&dash), "Could not add dashes to shaded path.");
1487             HRM(shadedPath->SetStrokeDashOffset(-2.0),
1488                 "Could not set dash offset for shaded path.");
1489         }
1490     }
1491     return S_OK;
1492 }
1493 
drawPath(const SkPath & platonicPath,const SkPaint & origPaint,bool pathIsMutable)1494 void SkXPSDevice::drawPath(const SkPath& platonicPath,
1495                            const SkPaint& origPaint,
1496                            bool pathIsMutable) {
1497     SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
1498 
1499     // nothing to draw
1500     if (this->cs().isEmpty(size(*this)) ||
1501         (paint->getAlpha() == 0 && paint->isSrcOver())) {
1502         return;
1503     }
1504 
1505     SkPath modifiedPath;
1506     const bool paintHasPathEffect = paint->getPathEffect()
1507                                  || paint->getStyle() != SkPaint::kFill_Style;
1508 
1509     //Apply pre-path matrix [Platonic-path -> Skeletal-path].
1510     SkMatrix matrix = this->localToDevice();
1511     SkPath* skeletalPath = const_cast<SkPath*>(&platonicPath);
1512 
1513     //Apply path effect [Skeletal-path -> Fillable-path].
1514     SkPath* fillablePath = skeletalPath;
1515     if (paintHasPathEffect) {
1516         if (!pathIsMutable) {
1517             fillablePath = &modifiedPath;
1518             pathIsMutable = true;
1519         }
1520         bool fill = skpathutils::FillPathWithPaint(*skeletalPath, *paint, fillablePath);
1521 
1522         SkPaint* writablePaint = paint.writable();
1523         writablePaint->setPathEffect(nullptr);
1524         if (fill) {
1525             writablePaint->setStyle(SkPaint::kFill_Style);
1526         } else {
1527             writablePaint->setStyle(SkPaint::kStroke_Style);
1528             writablePaint->setStrokeWidth(0);
1529         }
1530     }
1531 
1532     //Create the shaded path. This will be the path which is painted.
1533     SkTScopedComPtr<IXpsOMPath> shadedPath;
1534     HRVM(this->fXpsFactory->CreatePath(&shadedPath),
1535          "Could not create shaded path for path.");
1536 
1537     //Create the geometry for the shaded path.
1538     SkTScopedComPtr<IXpsOMGeometry> shadedGeometry;
1539     HRVM(this->fXpsFactory->CreateGeometry(&shadedGeometry),
1540          "Could not create shaded geometry for path.");
1541 
1542     //Add the geometry to the shaded path.
1543     HRVM(shadedPath->SetGeometryLocal(shadedGeometry.get()),
1544          "Could not add the shaded geometry to shaded path.");
1545 
1546     SkMaskFilter* filter = paint->getMaskFilter();
1547 
1548     //Determine if we will draw or shade and mask.
1549     if (filter) {
1550         if (paint->getStyle() != SkPaint::kFill_Style) {
1551             paint.writable()->setStyle(SkPaint::kFill_Style);
1552         }
1553     }
1554 
1555     //Set the brushes.
1556     BOOL fill;
1557     BOOL stroke;
1558     HRV(this->shadePath(shadedPath.get(),
1559                         *paint,
1560                         this->localToDevice(),
1561                         &fill,
1562                         &stroke));
1563 
1564     //Mask filter
1565     if (filter) {
1566         SkIRect clipIRect;
1567         SkVector ppuScale;
1568         this->convertToPpm(filter,
1569                            &matrix,
1570                            &ppuScale,
1571                            this->cs().bounds(size(*this)).roundOut(),
1572                            &clipIRect);
1573 
1574         //[Fillable-path -> Pixel-path]
1575         SkPath* pixelPath = pathIsMutable ? fillablePath : &modifiedPath;
1576         fillablePath->transform(matrix, pixelPath);
1577 
1578         SkMask* mask = nullptr;
1579 
1580         SkASSERT(SkPaint::kFill_Style == paint->getStyle() ||
1581                  (SkPaint::kStroke_Style == paint->getStyle() && 0 == paint->getStrokeWidth()));
1582         SkStrokeRec::InitStyle style = (SkPaint::kFill_Style == paint->getStyle())
1583                                             ? SkStrokeRec::kFill_InitStyle
1584                                             : SkStrokeRec::kHairline_InitStyle;
1585         //[Pixel-path -> Mask]
1586         SkMask rasteredMask;
1587         if (SkDraw::DrawToMask(
1588                         *pixelPath,
1589                         clipIRect,
1590                         filter,  //just to compute how much to draw.
1591                         &matrix,
1592                         &rasteredMask,
1593                         SkMask::kComputeBoundsAndRenderImage_CreateMode,
1594                         style)) {
1595 
1596             SkAutoMaskFreeImage rasteredAmi(rasteredMask.fImage);
1597             mask = &rasteredMask;
1598 
1599             //[Mask -> Mask]
1600             SkMask filteredMask;
1601             if (as_MFB(filter)->filterMask(&filteredMask, rasteredMask, matrix, nullptr)) {
1602                 mask = &filteredMask;
1603             }
1604             SkAutoMaskFreeImage filteredAmi(filteredMask.fImage);
1605 
1606             //Draw mask.
1607             HRV(this->applyMask(*mask, ppuScale, shadedPath.get()));
1608         }
1609         return;
1610     }
1611 
1612     //Get the figures from the shaded geometry.
1613     SkTScopedComPtr<IXpsOMGeometryFigureCollection> shadedFigures;
1614     HRVM(shadedGeometry->GetFigures(&shadedFigures),
1615          "Could not get shaded figures for shaded path.");
1616 
1617     bool xpsTransformsPath = true;
1618 
1619     //Set the fill rule.
1620     SkPath* xpsCompatiblePath = fillablePath;
1621     XPS_FILL_RULE xpsFillRule;
1622     switch (fillablePath->getFillType()) {
1623         case SkPathFillType::kWinding:
1624             xpsFillRule = XPS_FILL_RULE_NONZERO;
1625             break;
1626         case SkPathFillType::kEvenOdd:
1627             xpsFillRule = XPS_FILL_RULE_EVENODD;
1628             break;
1629         case SkPathFillType::kInverseWinding: {
1630             //[Fillable-path (inverse winding) -> XPS-path (inverse even odd)]
1631             if (!pathIsMutable) {
1632                 xpsCompatiblePath = &modifiedPath;
1633                 pathIsMutable = true;
1634             }
1635             if (!Simplify(*fillablePath, xpsCompatiblePath)) {
1636                 SkDEBUGF("Could not simplify inverse winding path.");
1637                 return;
1638             }
1639         }
1640         [[fallthrough]];  // The xpsCompatiblePath is now inverse even odd, so fall through.
1641         case SkPathFillType::kInverseEvenOdd: {
1642             const SkRect universe = SkRect::MakeLTRB(
1643                 0, 0,
1644                 this->fCurrentCanvasSize.fWidth,
1645                 this->fCurrentCanvasSize.fHeight);
1646             SkTScopedComPtr<IXpsOMGeometryFigure> addOneFigure;
1647             HRV(this->createXpsRect(universe, FALSE, TRUE, &addOneFigure));
1648             HRVM(shadedFigures->Append(addOneFigure.get()),
1649                  "Could not add even-odd flip figure to shaded path.");
1650             xpsTransformsPath = false;
1651             xpsFillRule = XPS_FILL_RULE_EVENODD;
1652             break;
1653         }
1654         default:
1655             SkDEBUGFAIL("Unknown SkPath::FillType.");
1656     }
1657     HRVM(shadedGeometry->SetFillRule(xpsFillRule),
1658          "Could not set fill rule for shaded path.");
1659 
1660     //Create the XPS transform, if possible.
1661     if (xpsTransformsPath) {
1662         SkTScopedComPtr<IXpsOMMatrixTransform> xpsTransform;
1663         HRV(this->createXpsTransform(matrix, &xpsTransform));
1664 
1665         if (xpsTransform.get()) {
1666             HRVM(shadedGeometry->SetTransformLocal(xpsTransform.get()),
1667                  "Could not set transform on shaded path.");
1668         } else {
1669             xpsTransformsPath = false;
1670         }
1671     }
1672 
1673     SkPath* devicePath = xpsCompatiblePath;
1674     if (!xpsTransformsPath) {
1675         //[Fillable-path -> Device-path]
1676         devicePath = pathIsMutable ? xpsCompatiblePath : &modifiedPath;
1677         xpsCompatiblePath->transform(matrix, devicePath);
1678     }
1679     HRV(this->addXpsPathGeometry(shadedFigures.get(),
1680                                  stroke, fill, *devicePath));
1681 
1682     HRV(this->clip(shadedPath.get()));
1683 
1684     //Add the path to the active visual collection.
1685     SkTScopedComPtr<IXpsOMVisualCollection> currentVisuals;
1686     HRVM(this->fCurrentXpsCanvas->GetVisuals(&currentVisuals),
1687          "Could not get current visuals for shaded path.");
1688     HRVM(currentVisuals->Append(shadedPath.get()),
1689          "Could not add shaded path to current visuals.");
1690 }
1691 
clip(IXpsOMVisual * xpsVisual)1692 HRESULT SkXPSDevice::clip(IXpsOMVisual* xpsVisual) {
1693     if (this->cs().isWideOpen()) {
1694         return S_OK;
1695     }
1696     SkPath clipPath;
1697     // clipPath.addRect(this->cs().bounds(size(*this)));
1698     SkClipStack_AsPath(this->cs(), &clipPath);
1699     // TODO: handle all the kinds of paths, like drawPath does
1700     return this->clipToPath(xpsVisual, clipPath, XPS_FILL_RULE_EVENODD);
1701 }
clipToPath(IXpsOMVisual * xpsVisual,const SkPath & clipPath,XPS_FILL_RULE fillRule)1702 HRESULT SkXPSDevice::clipToPath(IXpsOMVisual* xpsVisual,
1703                                 const SkPath& clipPath,
1704                                 XPS_FILL_RULE fillRule) {
1705     //Create the geometry.
1706     SkTScopedComPtr<IXpsOMGeometry> clipGeometry;
1707     HRM(this->fXpsFactory->CreateGeometry(&clipGeometry),
1708         "Could not create clip geometry.");
1709 
1710     //Get the figure collection of the geometry.
1711     SkTScopedComPtr<IXpsOMGeometryFigureCollection> clipFigures;
1712     HRM(clipGeometry->GetFigures(&clipFigures),
1713         "Could not get the clip figures.");
1714 
1715     //Create the figures into the geometry.
1716     HR(this->addXpsPathGeometry(
1717         clipFigures.get(),
1718         FALSE, TRUE, clipPath));
1719 
1720     HRM(clipGeometry->SetFillRule(fillRule),
1721         "Could not set fill rule.");
1722     HRM(xpsVisual->SetClipGeometryLocal(clipGeometry.get()),
1723         "Could not set clip geometry.");
1724 
1725     return S_OK;
1726 }
1727 
CreateTypefaceUse(const SkFont & font,TypefaceUse ** typefaceUse)1728 HRESULT SkXPSDevice::CreateTypefaceUse(const SkFont& font,
1729                                        TypefaceUse** typefaceUse) {
1730     SkTypeface* typeface = font.getTypefaceOrDefault();
1731 
1732     //Check cache.
1733     const SkTypefaceID typefaceID = typeface->uniqueID();
1734     for (TypefaceUse& current : *this->fTopTypefaces) {
1735         if (current.typefaceId == typefaceID) {
1736             *typefaceUse = &current;
1737             return S_OK;
1738         }
1739     }
1740 
1741     //TODO: create glyph only fonts
1742     //and let the host deal with what kind of font we're looking at.
1743     XPS_FONT_EMBEDDING embedding = XPS_FONT_EMBEDDING_RESTRICTED;
1744 
1745     SkTScopedComPtr<IStream> fontStream;
1746     int ttcIndex;
1747     std::unique_ptr<SkStreamAsset> fontData = typeface->openStream(&ttcIndex);
1748     if (!fontData) {
1749         return E_NOTIMPL;
1750     }
1751     //TODO: cannot handle FON fonts.
1752     HRM(SkIStream::CreateFromSkStream(fontData->duplicate(), &fontStream),
1753         "Could not create font stream.");
1754 
1755     const size_t size =
1756         std::size(L"/Resources/Fonts/" L_GUID_ID L".odttf");
1757     wchar_t buffer[size];
1758     wchar_t id[GUID_ID_LEN];
1759     HR(this->createId(id, GUID_ID_LEN));
1760     swprintf_s(buffer, size, L"/Resources/Fonts/%s.odttf", id);
1761 
1762     SkTScopedComPtr<IOpcPartUri> partUri;
1763     HRM(this->fXpsFactory->CreatePartUri(buffer, &partUri),
1764         "Could not create font resource part uri.");
1765 
1766     SkTScopedComPtr<IXpsOMFontResource> xpsFontResource;
1767     HRM(this->fXpsFactory->CreateFontResource(fontStream.get(),
1768                                               embedding,
1769                                               partUri.get(),
1770                                               FALSE,
1771                                               &xpsFontResource),
1772         "Could not create font resource.");
1773 
1774     //TODO: change openStream to return -1 for non-ttc, get rid of this.
1775     uint8_t* data = (uint8_t*)fontData->getMemoryBase();
1776     bool isTTC = (data &&
1777                   fontData->getLength() >= sizeof(SkTTCFHeader) &&
1778                   ((SkTTCFHeader*)data)->ttcTag == SkTTCFHeader::TAG);
1779 
1780     int glyphCount = typeface->countGlyphs();
1781 
1782     TypefaceUse& newTypefaceUse = this->fTopTypefaces->emplace_back(
1783         typefaceID,
1784         isTTC ? ttcIndex : -1,
1785         std::move(fontData),
1786         std::move(xpsFontResource),
1787         glyphCount);
1788 
1789     *typefaceUse = &newTypefaceUse;
1790     return S_OK;
1791 }
1792 
AddGlyphs(IXpsOMObjectFactory * xpsFactory,IXpsOMCanvas * canvas,const TypefaceUse * font,LPCWSTR text,XPS_GLYPH_INDEX * xpsGlyphs,UINT32 xpsGlyphsLen,XPS_POINT * origin,FLOAT fontSize,XPS_STYLE_SIMULATION sims,const SkMatrix & transform,const SkPaint & paint)1793 HRESULT SkXPSDevice::AddGlyphs(IXpsOMObjectFactory* xpsFactory,
1794                                IXpsOMCanvas* canvas,
1795                                const TypefaceUse* font,
1796                                LPCWSTR text,
1797                                XPS_GLYPH_INDEX* xpsGlyphs,
1798                                UINT32 xpsGlyphsLen,
1799                                XPS_POINT *origin,
1800                                FLOAT fontSize,
1801                                XPS_STYLE_SIMULATION sims,
1802                                const SkMatrix& transform,
1803                                const SkPaint& paint) {
1804     SkTScopedComPtr<IXpsOMGlyphs> glyphs;
1805     HRM(xpsFactory->CreateGlyphs(font->xpsFont.get(), &glyphs), "Could not create glyphs.");
1806     HRM(glyphs->SetFontFaceIndex(font->ttcIndex), "Could not set glyph font face index.");
1807 
1808     //XPS uses affine transformations for everything...
1809     //...except positioning text.
1810     bool useCanvasForClip;
1811     if (transform.isTranslate()) {
1812         origin->x += SkScalarToFLOAT(transform.getTranslateX());
1813         origin->y += SkScalarToFLOAT(transform.getTranslateY());
1814         useCanvasForClip = false;
1815     } else {
1816         SkTScopedComPtr<IXpsOMMatrixTransform> xpsMatrixToUse;
1817         HR(this->createXpsTransform(transform, &xpsMatrixToUse));
1818         if (xpsMatrixToUse.get()) {
1819             HRM(glyphs->SetTransformLocal(xpsMatrixToUse.get()),
1820                 "Could not set transform matrix.");
1821             useCanvasForClip = true;
1822         } else {
1823             SkDEBUGFAIL("Attempt to add glyphs in perspective.");
1824             useCanvasForClip = false;
1825         }
1826     }
1827 
1828     SkTScopedComPtr<IXpsOMGlyphsEditor> glyphsEditor;
1829     HRM(glyphs->GetGlyphsEditor(&glyphsEditor), "Could not get glyph editor.");
1830 
1831     if (text) {
1832         HRM(glyphsEditor->SetUnicodeString(text),
1833             "Could not set unicode string.");
1834     }
1835 
1836     if (xpsGlyphs) {
1837         HRM(glyphsEditor->SetGlyphIndices(xpsGlyphsLen, xpsGlyphs),
1838             "Could not set glyphs.");
1839     }
1840 
1841     HRM(glyphsEditor->ApplyEdits(), "Could not apply glyph edits.");
1842 
1843     SkTScopedComPtr<IXpsOMBrush> xpsFillBrush;
1844     HR(this->createXpsBrush(
1845             paint,
1846             &xpsFillBrush,
1847             useCanvasForClip ? nullptr : &transform));
1848 
1849     HRM(glyphs->SetFillBrushLocal(xpsFillBrush.get()),
1850         "Could not set fill brush.");
1851 
1852     HRM(glyphs->SetOrigin(origin), "Could not set glyph origin.");
1853 
1854     HRM(glyphs->SetFontRenderingEmSize(fontSize),
1855         "Could not set font size.");
1856 
1857     HRM(glyphs->SetStyleSimulations(sims),
1858         "Could not set style simulations.");
1859 
1860     SkTScopedComPtr<IXpsOMVisualCollection> visuals;
1861     HRM(canvas->GetVisuals(&visuals), "Could not get glyph canvas visuals.");
1862 
1863     if (!useCanvasForClip) {
1864         HR(this->clip(glyphs.get()));
1865         HRM(visuals->Append(glyphs.get()), "Could not add glyphs to canvas.");
1866     } else {
1867         SkTScopedComPtr<IXpsOMCanvas> glyphCanvas;
1868         HRM(this->fXpsFactory->CreateCanvas(&glyphCanvas),
1869             "Could not create glyph canvas.");
1870 
1871         SkTScopedComPtr<IXpsOMVisualCollection> glyphCanvasVisuals;
1872         HRM(glyphCanvas->GetVisuals(&glyphCanvasVisuals),
1873             "Could not get glyph visuals collection.");
1874 
1875         HRM(glyphCanvasVisuals->Append(glyphs.get()),
1876             "Could not add glyphs to page.");
1877         HR(this->clip(glyphCanvas.get()));
1878 
1879         HRM(visuals->Append(glyphCanvas.get()),
1880             "Could not add glyph canvas to page.");
1881     }
1882 
1883     return S_OK;
1884 }
1885 
text_must_be_pathed(const SkPaint & paint,const SkMatrix & matrix)1886 static bool text_must_be_pathed(const SkPaint& paint, const SkMatrix& matrix) {
1887     const SkPaint::Style style = paint.getStyle();
1888     return matrix.hasPerspective()
1889         || SkPaint::kStroke_Style == style
1890         || SkPaint::kStrokeAndFill_Style == style
1891         || paint.getMaskFilter()
1892     ;
1893 }
1894 
onDrawGlyphRunList(SkCanvas *,const sktext::GlyphRunList & glyphRunList,const SkPaint & initailPaint,const SkPaint & drawingPaint)1895 void SkXPSDevice::onDrawGlyphRunList(SkCanvas*,
1896                                      const sktext::GlyphRunList& glyphRunList,
1897                                      const SkPaint& initailPaint,
1898                                      const SkPaint& drawingPaint) {
1899     SkASSERT(!glyphRunList.hasRSXForm());
1900 
1901     for (const auto& run : glyphRunList) {
1902         const SkGlyphID* glyphIDs = run.glyphsIDs().data();
1903         size_t glyphCount = run.glyphsIDs().size();
1904         const SkFont& font = run.font();
1905 
1906         if (!glyphCount || !glyphIDs || font.getSize() <= 0) {
1907             continue;
1908         }
1909 
1910         TypefaceUse* typeface;
1911         if (FAILED(CreateTypefaceUse(font, &typeface)) ||
1912             text_must_be_pathed(drawingPaint, this->localToDevice())) {
1913             SkPath path;
1914             //TODO: make this work, Draw currently does not handle as well.
1915             //paint.getTextPath(text, byteLength, x, y, &path);
1916             //this->drawPath(path, paint, nullptr, true);
1917             //TODO: add automation "text"
1918             continue;
1919         }
1920 
1921         //TODO: handle font scale and skew in x (text_scale_skew)
1922 
1923         // Advance width and offsets for glyphs measured in hundredths of the font em size
1924         // (XPS Spec 5.1.3).
1925         FLOAT centemPerUnit = 100.0f / SkScalarToFLOAT(font.getSize());
1926         AutoSTMalloc<32, XPS_GLYPH_INDEX> xpsGlyphs(glyphCount);
1927         size_t numGlyphs = typeface->glyphsUsed.size();
1928         size_t actualGlyphCount = 0;
1929 
1930         for (size_t i = 0; i < glyphCount; ++i) {
1931             if (numGlyphs <= glyphIDs[i]) {
1932                 continue;
1933             }
1934             const SkPoint& position = run.positions()[i];
1935             XPS_GLYPH_INDEX& xpsGlyph = xpsGlyphs[actualGlyphCount++];
1936             xpsGlyph.index = glyphIDs[i];
1937             xpsGlyph.advanceWidth = 0.0f;
1938             xpsGlyph.horizontalOffset = (SkScalarToFloat(position.fX) * centemPerUnit);
1939             xpsGlyph.verticalOffset = (SkScalarToFloat(position.fY) * -centemPerUnit);
1940             typeface->glyphsUsed.set(xpsGlyph.index);
1941         }
1942 
1943         if (actualGlyphCount == 0) {
1944             return;
1945         }
1946 
1947         XPS_POINT origin = {
1948             glyphRunList.origin().x(),
1949             glyphRunList.origin().y(),
1950         };
1951 
1952         HRV(AddGlyphs(this->fXpsFactory.get(),
1953                       this->fCurrentXpsCanvas.get(),
1954                       typeface,
1955                       nullptr,
1956                       xpsGlyphs.get(), actualGlyphCount,
1957                       &origin,
1958                       SkScalarToFLOAT(font.getSize()),
1959                       XPS_STYLE_SIMULATION_NONE,
1960                       this->localToDevice(),
1961                       drawingPaint));
1962     }
1963 }
1964 
drawDevice(SkBaseDevice * dev,const SkSamplingOptions &,const SkPaint &)1965 void SkXPSDevice::drawDevice(SkBaseDevice* dev, const SkSamplingOptions&, const SkPaint&) {
1966     SkXPSDevice* that = static_cast<SkXPSDevice*>(dev);
1967     SkASSERT(that->fTopTypefaces == this->fTopTypefaces);
1968 
1969     SkTScopedComPtr<IXpsOMMatrixTransform> xpsTransform;
1970     HRVM(this->createXpsTransform(dev->getRelativeTransform(*this), &xpsTransform),
1971          "Could not create layer transform.");
1972     HRVM(that->fCurrentXpsCanvas->SetTransformLocal(xpsTransform.get()),
1973          "Could not set layer transform.");
1974 
1975     //Get the current visual collection and add the layer to it.
1976     SkTScopedComPtr<IXpsOMVisualCollection> currentVisuals;
1977     HRVM(this->fCurrentXpsCanvas->GetVisuals(&currentVisuals),
1978          "Could not get current visuals for layer.");
1979     HRVM(currentVisuals->Append(that->fCurrentXpsCanvas.get()),
1980          "Could not add layer to current visuals.");
1981 }
1982 
onCreateDevice(const CreateInfo & info,const SkPaint *)1983 SkBaseDevice* SkXPSDevice::onCreateDevice(const CreateInfo& info, const SkPaint*) {
1984 //Conditional for bug compatibility with PDF device.
1985 #if 0
1986     if (SkBaseDevice::kGeneral_Usage == info.fUsage) {
1987         return nullptr;
1988         //To what stream do we write?
1989         //SkXPSDevice* dev = new SkXPSDevice(this);
1990         //SkSize s = SkSize::Make(width, height);
1991         //dev->BeginCanvas(s, s, SkMatrix::I());
1992         //return dev;
1993     }
1994 #endif
1995     SkXPSDevice* dev = new SkXPSDevice(info.fInfo.dimensions());
1996     dev->fXpsFactory.reset(SkRefComPtr(fXpsFactory.get()));
1997     dev->fCurrentCanvasSize = this->fCurrentCanvasSize;
1998     dev->fCurrentUnitsPerMeter = this->fCurrentUnitsPerMeter;
1999     dev->fCurrentPixelsPerMeter = this->fCurrentPixelsPerMeter;
2000     dev->fTopTypefaces = this->fTopTypefaces;
2001     SkAssertResult(dev->createCanvasForLayer());
2002     return dev;
2003 }
2004 
drawOval(const SkRect & o,const SkPaint & p)2005 void SkXPSDevice::drawOval( const SkRect& o, const SkPaint& p) {
2006     SkPath path;
2007     path.addOval(o);
2008     this->drawPath(path, p, true);
2009 }
2010 
drawImageRect(const SkImage * image,const SkRect * src,const SkRect & dst,const SkSamplingOptions & sampling,const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)2011 void SkXPSDevice::drawImageRect(const SkImage* image,
2012                                 const SkRect* src,
2013                                 const SkRect& dst,
2014                                 const SkSamplingOptions& sampling,
2015                                 const SkPaint& paint,
2016                                 SkCanvas::SrcRectConstraint constraint) {
2017     // TODO: support gpu images
2018     SkBitmap bitmap;
2019     if (!as_IB(image)->getROPixels(nullptr, &bitmap)) {
2020         return;
2021     }
2022 
2023     SkRect bitmapBounds = SkRect::Make(bitmap.bounds());
2024     SkRect srcBounds = src ? *src : bitmapBounds;
2025     SkMatrix matrix = SkMatrix::RectToRect(srcBounds, dst);
2026     SkRect actualDst;
2027     if (!src || bitmapBounds.contains(*src)) {
2028         actualDst = dst;
2029     } else {
2030         if (!srcBounds.intersect(bitmapBounds)) {
2031             return;
2032         }
2033         matrix.mapRect(&actualDst, srcBounds);
2034     }
2035 
2036     auto bitmapShader = SkMakeBitmapShaderForPaint(paint, bitmap,
2037                                                    SkTileMode::kClamp, SkTileMode::kClamp,
2038                                                    sampling, &matrix, kNever_SkCopyPixelsMode);
2039     SkASSERT(bitmapShader);
2040     if (!bitmapShader) { return; }
2041     SkPaint paintWithShader(paint);
2042     paintWithShader.setStyle(SkPaint::kFill_Style);
2043     paintWithShader.setShader(std::move(bitmapShader));
2044     this->drawRect(actualDst, paintWithShader);
2045 }
2046 #endif//defined(SK_BUILD_FOR_WIN)
2047