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