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