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