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