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