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