• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/core/SkDevice.h"
9 
10 #include "include/core/SkColorFilter.h"
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkImageFilter.h"
13 #include "include/core/SkPathMeasure.h"
14 #include "include/core/SkRSXform.h"
15 #include "include/core/SkShader.h"
16 #include "include/core/SkVertices.h"
17 #include "include/private/SkTo.h"
18 #include "src/core/SkDraw.h"
19 #include "src/core/SkGlyphRun.h"
20 #include "src/core/SkImageFilterCache.h"
21 #include "src/core/SkImageFilter_Base.h"
22 #include "src/core/SkImagePriv.h"
23 #include "src/core/SkLatticeIter.h"
24 #include "src/core/SkMarkerStack.h"
25 #include "src/core/SkMatrixPriv.h"
26 #include "src/core/SkPathPriv.h"
27 #include "src/core/SkRasterClip.h"
28 #include "src/core/SkSpecialImage.h"
29 #include "src/core/SkTLazy.h"
30 #include "src/core/SkTextBlobPriv.h"
31 #include "src/core/SkUtils.h"
32 #include "src/image/SkImage_Base.h"
33 #include "src/shaders/SkLocalMatrixShader.h"
34 #include "src/utils/SkPatchUtils.h"
35 
SkBaseDevice(const SkImageInfo & info,const SkSurfaceProps & surfaceProps)36 SkBaseDevice::SkBaseDevice(const SkImageInfo& info, const SkSurfaceProps& surfaceProps)
37         : SkMatrixProvider(/* localToDevice = */ SkMatrix::I())
38         , fInfo(info)
39         , fSurfaceProps(surfaceProps) {
40     fDeviceToGlobal.reset();
41     fGlobalToDevice.reset();
42 }
43 
setDeviceCoordinateSystem(const SkMatrix & deviceToGlobal,const SkM44 & localToDevice,int bufferOriginX,int bufferOriginY)44 void SkBaseDevice::setDeviceCoordinateSystem(const SkMatrix& deviceToGlobal,
45                                              const SkM44& localToDevice,
46                                              int bufferOriginX,
47                                              int bufferOriginY) {
48     fDeviceToGlobal = deviceToGlobal;
49     fDeviceToGlobal.normalizePerspective();
50     SkAssertResult(deviceToGlobal.invert(&fGlobalToDevice));
51 
52     fLocalToDevice = localToDevice;
53     fLocalToDevice.normalizePerspective();
54     if (bufferOriginX | bufferOriginY) {
55         fDeviceToGlobal.preTranslate(bufferOriginX, bufferOriginY);
56         fGlobalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
57         fLocalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
58     }
59     fLocalToDevice33 = fLocalToDevice.asM33();
60 }
61 
setGlobalCTM(const SkM44 & ctm)62 void SkBaseDevice::setGlobalCTM(const SkM44& ctm) {
63     fLocalToDevice = ctm;
64     fLocalToDevice.normalizePerspective();
65     if (!fGlobalToDevice.isIdentity()) {
66         // Map from the global CTM state to this device's coordinate system.
67         fLocalToDevice.postConcat(SkM44(fGlobalToDevice));
68     }
69     fLocalToDevice33 = fLocalToDevice.asM33();
70 }
71 
isPixelAlignedToGlobal() const72 bool SkBaseDevice::isPixelAlignedToGlobal() const {
73     return fDeviceToGlobal.isTranslate() &&
74            SkScalarIsInt(fDeviceToGlobal.getTranslateX()) &&
75            SkScalarIsInt(fDeviceToGlobal.getTranslateY());
76 }
77 
getOrigin() const78 SkIPoint SkBaseDevice::getOrigin() const {
79     // getOrigin() is deprecated, the old origin has been moved into the fDeviceToGlobal matrix.
80     // This extracts the origin from the matrix, but asserts that a more complicated coordinate
81     // space hasn't been set of the device. This function can be removed once existing use cases
82     // have been updated to use the device-to-global matrix instead or have themselves been removed
83     // (e.g. Android's device-space clip regions are going away, and are not compatible with the
84     // generalized device coordinate system).
85     SkASSERT(this->isPixelAlignedToGlobal());
86     return SkIPoint::Make(SkScalarFloorToInt(fDeviceToGlobal.getTranslateX()),
87                           SkScalarFloorToInt(fDeviceToGlobal.getTranslateY()));
88 }
89 
getRelativeTransform(const SkBaseDevice & dstDevice) const90 SkMatrix SkBaseDevice::getRelativeTransform(const SkBaseDevice& dstDevice) const {
91     // To get the transform from this space to the other device's, transform from our space to
92     // global and then from global to the other device.
93     return SkMatrix::Concat(dstDevice.fGlobalToDevice, fDeviceToGlobal);
94 }
95 
getLocalToMarker(uint32_t id,SkM44 * localToMarker) const96 bool SkBaseDevice::getLocalToMarker(uint32_t id, SkM44* localToMarker) const {
97     // The marker stack stores CTM snapshots, which are "marker to global" matrices.
98     // We ask for the (cached) inverse, which is a "global to marker" matrix.
99     SkM44 globalToMarker;
100     // ID 0 is special, and refers to the CTM (local-to-global)
101     if (fMarkerStack && (id == 0 || fMarkerStack->findMarkerInverse(id, &globalToMarker))) {
102         if (localToMarker) {
103             // globalToMarker will still be the identity if id is zero
104             *localToMarker = globalToMarker * SkM44(fDeviceToGlobal) * fLocalToDevice;
105         }
106         return true;
107     }
108     return false;
109 }
110 
is_int(float x)111 static inline bool is_int(float x) {
112     return x == (float) sk_float_round2int(x);
113 }
114 
drawRegion(const SkRegion & region,const SkPaint & paint)115 void SkBaseDevice::drawRegion(const SkRegion& region, const SkPaint& paint) {
116     const SkMatrix& localToDevice = this->localToDevice();
117     bool isNonTranslate = localToDevice.getType() & ~(SkMatrix::kTranslate_Mask);
118     bool complexPaint = paint.getStyle() != SkPaint::kFill_Style || paint.getMaskFilter() ||
119                         paint.getPathEffect();
120     bool antiAlias = paint.isAntiAlias() && (!is_int(localToDevice.getTranslateX()) ||
121                                              !is_int(localToDevice.getTranslateY()));
122     if (isNonTranslate || complexPaint || antiAlias) {
123         SkPath path;
124         region.getBoundaryPath(&path);
125         path.setIsVolatile(true);
126         return this->drawPath(path, paint, true);
127     }
128 
129     SkRegion::Iterator it(region);
130     while (!it.done()) {
131         this->drawRect(SkRect::Make(it.rect()), paint);
132         it.next();
133     }
134 }
135 
drawArc(const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const SkPaint & paint)136 void SkBaseDevice::drawArc(const SkRect& oval, SkScalar startAngle,
137                            SkScalar sweepAngle, bool useCenter, const SkPaint& paint) {
138     SkPath path;
139     bool isFillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
140     SkPathPriv::CreateDrawArcPath(&path, oval, startAngle, sweepAngle, useCenter,
141                                   isFillNoPathEffect);
142     this->drawPath(path, paint);
143 }
144 
drawDRRect(const SkRRect & outer,const SkRRect & inner,const SkPaint & paint)145 void SkBaseDevice::drawDRRect(const SkRRect& outer,
146                               const SkRRect& inner, const SkPaint& paint) {
147     SkPath path;
148     path.addRRect(outer);
149     path.addRRect(inner);
150     path.setFillType(SkPathFillType::kEvenOdd);
151     path.setIsVolatile(true);
152 
153     this->drawPath(path, paint, true);
154 }
155 
drawPatch(const SkPoint cubics[12],const SkColor colors[4],const SkPoint texCoords[4],SkBlendMode bmode,const SkPaint & paint)156 void SkBaseDevice::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
157                              const SkPoint texCoords[4], SkBlendMode bmode, const SkPaint& paint) {
158     SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &this->localToDevice());
159     auto vertices = SkPatchUtils::MakeVertices(cubics, colors, texCoords, lod.width(), lod.height(),
160                                                this->imageInfo().colorSpace());
161     if (vertices) {
162         this->drawVertices(vertices.get(), bmode, paint);
163     }
164 }
165 
drawImageLattice(const SkImage * image,const SkCanvas::Lattice & lattice,const SkRect & dst,SkFilterMode filter,const SkPaint & paint)166 void SkBaseDevice::drawImageLattice(const SkImage* image, const SkCanvas::Lattice& lattice,
167                                     const SkRect& dst, SkFilterMode filter, const SkPaint& paint) {
168     SkLatticeIter iter(lattice, dst);
169 
170     SkRect srcR, dstR;
171     SkColor c;
172     bool isFixedColor = false;
173     const SkImageInfo info = SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType);
174 
175     while (iter.next(&srcR, &dstR, &isFixedColor, &c)) {
176         // TODO: support this fast-path for GPU images
177         if (isFixedColor || (srcR.width() <= 1.0f && srcR.height() <= 1.0f &&
178                              image->readPixels(nullptr, info, &c, 4, srcR.fLeft, srcR.fTop))) {
179               // Fast draw with drawRect, if this is a patch containing a single color
180               // or if this is a patch containing a single pixel.
181               if (0 != c || !paint.isSrcOver()) {
182                    SkPaint paintCopy(paint);
183                    int alpha = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
184                    paintCopy.setColor(SkColorSetA(c, alpha));
185                    this->drawRect(dstR, paintCopy);
186               }
187         } else {
188             this->drawImageRect(image, &srcR, dstR, SkSamplingOptions(filter), paint,
189                                 SkCanvas::kStrict_SrcRectConstraint);
190         }
191     }
192 }
193 
quad_to_tris(SkPoint tris[6],const SkPoint quad[4])194 static SkPoint* quad_to_tris(SkPoint tris[6], const SkPoint quad[4]) {
195     tris[0] = quad[0];
196     tris[1] = quad[1];
197     tris[2] = quad[2];
198 
199     tris[3] = quad[0];
200     tris[4] = quad[2];
201     tris[5] = quad[3];
202 
203     return tris + 6;
204 }
205 
drawAtlas(const SkImage * atlas,const SkRSXform xform[],const SkRect tex[],const SkColor colors[],int quadCount,SkBlendMode mode,const SkSamplingOptions & sampling,const SkPaint & paint)206 void SkBaseDevice::drawAtlas(const SkImage* atlas, const SkRSXform xform[],
207                              const SkRect tex[], const SkColor colors[], int quadCount,
208                              SkBlendMode mode, const SkSamplingOptions& sampling,
209                              const SkPaint& paint) {
210     const int triCount = quadCount << 1;
211     const int vertexCount = triCount * 3;
212     uint32_t flags = SkVertices::kHasTexCoords_BuilderFlag;
213     if (colors) {
214         flags |= SkVertices::kHasColors_BuilderFlag;
215     }
216     SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, vertexCount, 0, flags);
217 
218     SkPoint* vPos = builder.positions();
219     SkPoint* vTex = builder.texCoords();
220     SkColor* vCol = builder.colors();
221     for (int i = 0; i < quadCount; ++i) {
222         SkPoint tmp[4];
223         xform[i].toQuad(tex[i].width(), tex[i].height(), tmp);
224         vPos = quad_to_tris(vPos, tmp);
225 
226         tex[i].toQuad(tmp);
227         vTex = quad_to_tris(vTex, tmp);
228 
229         if (colors) {
230             sk_memset32(vCol, colors[i], 6);
231             vCol += 6;
232         }
233     }
234     SkPaint p(paint);
235     p.setShader(atlas->makeShader(sampling));
236     this->drawVertices(builder.detach().get(), mode, p);
237 }
238 
239 
drawEdgeAAQuad(const SkRect & r,const SkPoint clip[4],SkCanvas::QuadAAFlags aa,const SkColor4f & color,SkBlendMode mode)240 void SkBaseDevice::drawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], SkCanvas::QuadAAFlags aa,
241                                   const SkColor4f& color, SkBlendMode mode) {
242     SkPaint paint;
243     paint.setColor4f(color);
244     paint.setBlendMode(mode);
245     paint.setAntiAlias(aa == SkCanvas::kAll_QuadAAFlags);
246 
247     if (clip) {
248         // Draw the clip directly as a quad since it's a filled color with no local coords
249         SkPath clipPath;
250         clipPath.addPoly(clip, 4, true);
251         this->drawPath(clipPath, paint);
252     } else {
253         this->drawRect(r, paint);
254     }
255 }
256 
drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[],int count,const SkPoint dstClips[],const SkMatrix preViewMatrices[],const SkSamplingOptions & sampling,const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)257 void SkBaseDevice::drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[], int count,
258                                       const SkPoint dstClips[], const SkMatrix preViewMatrices[],
259                                       const SkSamplingOptions& sampling, const SkPaint& paint,
260                                       SkCanvas::SrcRectConstraint constraint) {
261     SkASSERT(paint.getStyle() == SkPaint::kFill_Style);
262     SkASSERT(!paint.getPathEffect());
263 
264     SkPaint entryPaint = paint;
265     const SkM44 baseLocalToDevice = this->localToDevice44();
266     int clipIndex = 0;
267     for (int i = 0; i < count; ++i) {
268         // TODO: Handle per-edge AA. Right now this mirrors the SkiaRenderer component of Chrome
269         // which turns off antialiasing unless all four edges should be antialiased. This avoids
270         // seaming in tiled composited layers.
271         entryPaint.setAntiAlias(images[i].fAAFlags == SkCanvas::kAll_QuadAAFlags);
272         entryPaint.setAlphaf(paint.getAlphaf() * images[i].fAlpha);
273 
274         bool needsRestore = false;
275         SkASSERT(images[i].fMatrixIndex < 0 || preViewMatrices);
276         if (images[i].fMatrixIndex >= 0) {
277             this->save();
278             this->setLocalToDevice(baseLocalToDevice *
279                                    SkM44(preViewMatrices[images[i].fMatrixIndex]));
280             needsRestore = true;
281         }
282 
283         SkASSERT(!images[i].fHasClip || dstClips);
284         if (images[i].fHasClip) {
285             // Since drawImageRect requires a srcRect, the dst clip is implemented as a true clip
286             if (!needsRestore) {
287                 this->save();
288                 needsRestore = true;
289             }
290             SkPath clipPath;
291             clipPath.addPoly(dstClips + clipIndex, 4, true);
292             this->clipPath(clipPath, SkClipOp::kIntersect, entryPaint.isAntiAlias());
293             clipIndex += 4;
294         }
295         this->drawImageRect(images[i].fImage.get(), &images[i].fSrcRect, images[i].fDstRect,
296                             sampling, entryPaint, constraint);
297         if (needsRestore) {
298             this->restoreLocal(baseLocalToDevice);
299         }
300     }
301 }
302 
303 ///////////////////////////////////////////////////////////////////////////////////////////////////
304 
drawDrawable(SkDrawable * drawable,const SkMatrix * matrix,SkCanvas * canvas)305 void SkBaseDevice::drawDrawable(SkDrawable* drawable, const SkMatrix* matrix, SkCanvas* canvas) {
306     drawable->draw(canvas, matrix);
307 }
308 
309 ///////////////////////////////////////////////////////////////////////////////////////////////////
310 
drawSpecial(SkSpecialImage *,const SkMatrix &,const SkSamplingOptions &,const SkPaint &)311 void SkBaseDevice::drawSpecial(SkSpecialImage*, const SkMatrix&, const SkSamplingOptions&,
312                                const SkPaint&) {}
makeSpecial(const SkBitmap &)313 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkBitmap&) { return nullptr; }
makeSpecial(const SkImage *)314 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkImage*) { return nullptr; }
snapSpecial(const SkIRect &,bool)315 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial(const SkIRect&, bool) { return nullptr; }
snapSpecial()316 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial() {
317     return this->snapSpecial(SkIRect::MakeWH(this->width(), this->height()));
318 }
319 
drawDevice(SkBaseDevice * device,const SkSamplingOptions & sampling,const SkPaint & paint)320 void SkBaseDevice::drawDevice(SkBaseDevice* device, const SkSamplingOptions& sampling,
321                               const SkPaint& paint) {
322     sk_sp<SkSpecialImage> deviceImage = device->snapSpecial();
323     if (deviceImage) {
324         this->drawSpecial(deviceImage.get(), device->getRelativeTransform(*this), sampling, paint);
325     }
326 }
327 
drawFilteredImage(const skif::Mapping & mapping,SkSpecialImage * src,const SkImageFilter * filter,const SkSamplingOptions & sampling,const SkPaint & paint)328 void SkBaseDevice::drawFilteredImage(const skif::Mapping& mapping, SkSpecialImage* src,
329                                      const SkImageFilter* filter, const SkSamplingOptions& sampling,
330                                      const SkPaint& paint) {
331     SkASSERT(!paint.getImageFilter() && !paint.getMaskFilter());
332     using For = skif::Usage;
333 
334     skif::LayerSpace<SkIRect> targetOutput = mapping.deviceToLayer(
335             skif::DeviceSpace<SkIRect>(this->devClipBounds()));
336 
337     // FIXME If the saved layer (so src) was created to use F16, should we do all image filtering
338     // in F16 and then only flatten to the destination color encoding at the end?
339     // Currently, this context converts everything to the dst color type ASAP.
340     SkColorType colorType = this->imageInfo().colorType();
341     if (colorType == kUnknown_SkColorType) {
342         colorType = kRGBA_8888_SkColorType;
343     }
344 
345     // getImageFilterCache returns a bare image filter cache pointer that must be ref'ed until the
346     // filter's filterImage(ctx) function returns.
347     sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
348     skif::Context ctx(mapping, targetOutput, cache.get(), colorType, this->imageInfo().colorSpace(),
349                       skif::FilterResult<For::kInput>(sk_ref_sp(src)));
350 
351     SkIPoint offset;
352     sk_sp<SkSpecialImage> result = as_IFB(filter)->filterImage(ctx).imageAndOffset(&offset);
353     if (result) {
354         SkMatrix deviceMatrixWithOffset = mapping.deviceMatrix();
355         deviceMatrixWithOffset.preTranslate(offset.fX, offset.fY);
356         this->drawSpecial(result.get(), deviceMatrixWithOffset, sampling, paint);
357     }
358 }
359 
360 ///////////////////////////////////////////////////////////////////////////////////////////////////
361 
readPixels(const SkPixmap & pm,int x,int y)362 bool SkBaseDevice::readPixels(const SkPixmap& pm, int x, int y) {
363     return this->onReadPixels(pm, x, y);
364 }
365 
writePixels(const SkPixmap & pm,int x,int y)366 bool SkBaseDevice::writePixels(const SkPixmap& pm, int x, int y) {
367     return this->onWritePixels(pm, x, y);
368 }
369 
onWritePixels(const SkPixmap &,int,int)370 bool SkBaseDevice::onWritePixels(const SkPixmap&, int, int) {
371     return false;
372 }
373 
onReadPixels(const SkPixmap &,int x,int y)374 bool SkBaseDevice::onReadPixels(const SkPixmap&, int x, int y) {
375     return false;
376 }
377 
accessPixels(SkPixmap * pmap)378 bool SkBaseDevice::accessPixels(SkPixmap* pmap) {
379     SkPixmap tempStorage;
380     if (nullptr == pmap) {
381         pmap = &tempStorage;
382     }
383     return this->onAccessPixels(pmap);
384 }
385 
peekPixels(SkPixmap * pmap)386 bool SkBaseDevice::peekPixels(SkPixmap* pmap) {
387     SkPixmap tempStorage;
388     if (nullptr == pmap) {
389         pmap = &tempStorage;
390     }
391     return this->onPeekPixels(pmap);
392 }
393 
394 //////////////////////////////////////////////////////////////////////////////////////////
395 
396 #include "src/core/SkUtils.h"
397 
398 
399 // TODO: This does not work for arbitrary shader DAGs (when there is no single leaf local matrix).
400 // What we really need is proper post-LM plumbing for shaders.
make_post_inverse_lm(const SkShader * shader,const SkMatrix & m)401 static sk_sp<SkShader> make_post_inverse_lm(const SkShader* shader, const SkMatrix& m) {
402     SkMatrix inverse;
403     if (!shader || !m.invert(&inverse)) {
404         return nullptr;
405     }
406 
407     // Normal LMs pre-compose.  In order to push a post local matrix, we shoot for
408     // something along these lines (where all new components are pre-composed):
409     //
410     //   new_lm X current_lm == current_lm X inv(current_lm) X new_lm X current_lm
411     //
412     // We also have two sources of local matrices:
413     //   - the actual shader lm
414     //   - outer lms applied via SkLocalMatrixShader
415 
416     SkMatrix outer_lm;
417     const auto nested_shader = as_SB(shader)->makeAsALocalMatrixShader(&outer_lm);
418     if (nested_shader) {
419         // unfurl the shader
420         shader = nested_shader.get();
421     } else {
422         outer_lm.reset();
423     }
424 
425     const auto lm = *as_SB(shader)->totalLocalMatrix(nullptr);
426     SkMatrix lm_inv;
427     if (!lm.invert(&lm_inv)) {
428         return nullptr;
429     }
430 
431     // Note: since we unfurled the shader above, we don't need to apply an outer_lm inverse
432     return shader->makeWithLocalMatrix(lm_inv * inverse * lm * outer_lm);
433 }
434 
drawGlyphRunList(const SkGlyphRunList & glyphRunList,const SkPaint & paint)435 void SkBaseDevice::drawGlyphRunList(const SkGlyphRunList& glyphRunList, const SkPaint& paint) {
436     if (!this->localToDevice().isFinite()) {
437         return;
438     }
439 
440     if (!glyphRunList.hasRSXForm()) {
441         this->onDrawGlyphRunList(glyphRunList, paint);
442     } else {
443         this->simplifyGlyphRunRSXFormAndRedraw(glyphRunList, paint);
444     }
445 }
446 
simplifyGlyphRunRSXFormAndRedraw(const SkGlyphRunList & glyphRunList,const SkPaint & paint)447 void SkBaseDevice::simplifyGlyphRunRSXFormAndRedraw(const SkGlyphRunList& glyphRunList,
448                                                     const SkPaint& paint) {
449     for (const SkGlyphRun& run : glyphRunList) {
450         if (run.scaledRotations().empty()) {
451             this->drawGlyphRunList(SkGlyphRunList{run, run.sourceBounds(paint), {0, 0}}, paint);
452         } else {
453             SkPoint origin = glyphRunList.origin();
454             SkPoint sharedPos{0, 0};    // we're at the origin
455             SkGlyphID sharedGlyphID;
456             SkGlyphRun glyphRun {
457                     run.font(),
458                     SkSpan<const SkPoint>{&sharedPos, 1},
459                     SkSpan<const SkGlyphID>{&sharedGlyphID, 1},
460                     SkSpan<const char>{},
461                     SkSpan<const uint32_t>{},
462                     SkSpan<const SkVector>{}
463             };
464 
465             const SkM44 originalLocalToDevice = this->localToDevice44();
466             for (auto [i, glyphID, pos] : SkMakeEnumerate(run.source())) {
467                 sharedGlyphID = glyphID;
468                 auto [scos, ssin] = run.scaledRotations()[i];
469                 SkRSXform rsxForm = SkRSXform::Make(scos, ssin, pos.x(), pos.y());
470                 SkMatrix glyphToLocal;
471                 glyphToLocal.setRSXform(rsxForm).postTranslate(origin.x(), origin.y());
472 
473                 // We want to rotate each glyph by the rsxform, but we don't want to rotate "space"
474                 // (i.e. the shader that cares about the ctm) so we have to undo our little ctm
475                 // trick with a localmatrixshader so that the shader draws as if there was no
476                 // change to the ctm.
477                 SkPaint invertingPaint{paint};
478                 invertingPaint.setShader(make_post_inverse_lm(paint.getShader(), glyphToLocal));
479                 this->setLocalToDevice(originalLocalToDevice * SkM44(glyphToLocal));
480                 this->drawGlyphRunList(
481                     SkGlyphRunList{glyphRun, glyphRun.sourceBounds(paint), {0, 0}}, invertingPaint);
482             }
483             this->setLocalToDevice(originalLocalToDevice);
484         }
485     }
486 }
487 
488 //////////////////////////////////////////////////////////////////////////////////////////
489 
makeSurface(SkImageInfo const &,SkSurfaceProps const &)490 sk_sp<SkSurface> SkBaseDevice::makeSurface(SkImageInfo const&, SkSurfaceProps const&) {
491     return nullptr;
492 }
493 
494 //////////////////////////////////////////////////////////////////////////////////////////
495 
onSave()496 void SkNoPixelsDevice::onSave() {
497     SkASSERT(!fClipStack.empty());
498     fClipStack.back().fDeferredSaveCount++;
499 }
500 
onRestore()501 void SkNoPixelsDevice::onRestore() {
502     SkASSERT(!fClipStack.empty());
503     if (fClipStack.back().fDeferredSaveCount > 0) {
504         fClipStack.back().fDeferredSaveCount--;
505     } else {
506         fClipStack.pop_back();
507         SkASSERT(!fClipStack.empty());
508     }
509 }
510 
writableClip()511 SkConservativeClip& SkNoPixelsDevice::writableClip() {
512     SkASSERT(!fClipStack.empty());
513     ClipState& current = fClipStack.back();
514     if (current.fDeferredSaveCount > 0) {
515         current.fDeferredSaveCount--;
516         return fClipStack.push_back(ClipState(current.fClip)).fClip;
517     } else {
518         return current.fClip;
519     }
520 }
521 
onClipRect(const SkRect & rect,SkClipOp op,bool aa)522 void SkNoPixelsDevice::onClipRect(const SkRect& rect, SkClipOp op, bool aa) {
523     this->writableClip().opRect(rect, this->localToDevice(), this->bounds(), (SkRegion::Op) op, aa);
524 }
525 
onClipRRect(const SkRRect & rrect,SkClipOp op,bool aa)526 void SkNoPixelsDevice::onClipRRect(const SkRRect& rrect, SkClipOp op, bool aa) {
527     this->writableClip().opRRect(rrect, this->localToDevice(), this->bounds(),
528                                  (SkRegion::Op) op, aa);
529 }
530 
onClipPath(const SkPath & path,SkClipOp op,bool aa)531 void SkNoPixelsDevice::onClipPath(const SkPath& path, SkClipOp op, bool aa) {
532     this->writableClip().opPath(path, this->localToDevice(), this->bounds(),
533                             (SkRegion::Op) op, aa);
534 }
535 
onClipRegion(const SkRegion & globalRgn,SkClipOp op)536 void SkNoPixelsDevice::onClipRegion(const SkRegion& globalRgn, SkClipOp op) {
537     if (globalRgn.isEmpty()) {
538         this->writableClip().setEmpty();
539     } else if (this->isPixelAlignedToGlobal()) {
540         SkIPoint origin = this->getOrigin();
541         SkRegion deviceRgn(globalRgn);
542         deviceRgn.translate(-origin.fX, -origin.fY);
543         this->writableClip().opRegion(deviceRgn, (SkRegion::Op) op);
544     } else {
545         this->writableClip().opRect(SkRect::Make(globalRgn.getBounds()), this->globalToDevice(),
546                                     this->bounds(), (SkRegion::Op) op, false);
547     }
548 }
549 
onClipShader(sk_sp<SkShader> shader)550 void SkNoPixelsDevice::onClipShader(sk_sp<SkShader> shader) {
551     this->writableClip().opShader(std::move(shader));
552 }
553 
onReplaceClip(const SkIRect & rect)554 void SkNoPixelsDevice::onReplaceClip(const SkIRect& rect) {
555     SkIRect deviceRect = this->globalToDevice().mapRect(SkRect::Make(rect)).round();
556     if (!deviceRect.intersect(this->bounds())) {
557         deviceRect.setEmpty();
558     }
559     this->writableClip().setRect(deviceRect);
560 }
561 
onSetDeviceClipRestriction(SkIRect * mutableClipRestriction)562 void SkNoPixelsDevice::onSetDeviceClipRestriction(SkIRect* mutableClipRestriction) {
563     if (!mutableClipRestriction || mutableClipRestriction->isEmpty()) {
564         // The subset clip restriction is gone, so just store the actual device bounds as the limit
565         fDeviceClipRestriction.setEmpty();
566     } else {
567         fDeviceClipRestriction =
568                 this->globalToDevice().mapRect(SkRect::Make(*mutableClipRestriction)).round();
569         // Besides affecting future ops, it acts as an immediate intersection
570         this->writableClip().opIRect(fDeviceClipRestriction, SkRegion::kIntersect_Op);
571     }
572 }
573 
onGetClipType() const574 SkBaseDevice::ClipType SkNoPixelsDevice::onGetClipType() const {
575     const auto& clip = this->clip();
576     if (clip.isEmpty()) {
577         return ClipType::kEmpty;
578     } else if (clip.isRect()) {
579         return ClipType::kRect;
580     } else {
581         return ClipType::kComplex;
582     }
583 }
584