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