SkXPSDevice.cpp 80 KB

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