1 /*
2 * Copyright 2008 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/core/SkCanvas.h"
9
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkBitmap.h"
12 #include "include/core/SkBlendMode.h"
13 #include "include/core/SkBlender.h"
14 #include "include/core/SkBlurTypes.h"
15 #include "include/core/SkColorFilter.h"
16 #include "include/core/SkColorSpace.h"
17 #include "include/core/SkColorType.h"
18 #include "include/core/SkImage.h"
19 #include "include/core/SkImageFilter.h"
20 #include "include/core/SkMaskFilter.h"
21 #include "include/core/SkPath.h"
22 #include "include/core/SkPathEffect.h"
23 #include "include/core/SkPicture.h"
24 #include "include/core/SkPixmap.h"
25 #include "include/core/SkRRect.h"
26 #include "include/core/SkRSXform.h"
27 #include "include/core/SkRasterHandleAllocator.h"
28 #include "include/core/SkRefCnt.h"
29 #include "include/core/SkRegion.h"
30 #include "include/core/SkShader.h"
31 #include "include/core/SkStrokeRec.h"
32 #include "include/core/SkSurface.h"
33 #include "include/core/SkTextBlob.h"
34 #include "include/core/SkTileMode.h"
35 #include "include/core/SkTypes.h"
36 #include "include/core/SkVertices.h"
37 #include "include/private/base/SkDebug.h"
38 #include "include/private/base/SkFloatingPoint.h"
39 #include "include/private/base/SkSafe32.h"
40 #include "include/private/base/SkTPin.h"
41 #include "include/private/base/SkTemplates.h"
42 #include "include/private/base/SkTo.h"
43 #include "include/private/chromium/Slug.h"
44 #include "include/utils/SkNoDrawCanvas.h"
45 #include "src/base/SkEnumBitMask.h"
46 #include "src/base/SkMSAN.h"
47 #include "src/core/SkBlenderBase.h"
48 #include "src/core/SkBlurMaskFilterImpl.h"
49 #include "src/core/SkCanvasPriv.h"
50 #include "src/core/SkDevice.h"
51 #include "src/core/SkImageFilterTypes.h"
52 #include "src/core/SkImageFilter_Base.h"
53 #include "src/core/SkImagePriv.h"
54 #include "src/core/SkLatticeIter.h"
55 #include "src/core/SkMaskFilterBase.h"
56 #include "src/core/SkMatrixPriv.h"
57 #include "src/core/SkPaintPriv.h"
58 #include "src/core/SkSpecialImage.h"
59 #include "src/core/SkSurfacePriv.h"
60 #include "src/core/SkTraceEvent.h"
61 #include "src/core/SkVerticesPriv.h"
62 #include "src/effects/colorfilters/SkColorFilterBase.h"
63 #include "src/image/SkSurface_Base.h"
64 #include "src/text/GlyphRun.h"
65 #include "src/utils/SkPatchUtils.h"
66
67 #include <algorithm>
68 #include <memory>
69 #include <new>
70 #include <optional>
71 #include <tuple>
72 #include <utility>
73
74 #define RETURN_ON_NULL(ptr) do { if (nullptr == (ptr)) return; } while (0)
75 #define RETURN_ON_FALSE(pred) do { if (!(pred)) return; } while (0)
76
77 // This is a test: static_assert with no message is a c++17 feature,
78 // and std::max() is constexpr only since the c++14 stdlib.
79 static_assert(std::max(3,4) == 4);
80
81 using Slug = sktext::gpu::Slug;
82
83 ///////////////////////////////////////////////////////////////////////////////////////////////////
84
SK_MAKE_BITMASK_OPS(SkCanvas::PredrawFlags)85 SK_MAKE_BITMASK_OPS(SkCanvas::PredrawFlags)
86
87 /*
88 * Return true if the drawing this rect would hit every pixels in the canvas.
89 *
90 * Returns false if
91 * - rect does not contain the canvas' bounds
92 * - paint is not fill
93 * - paint would blur or otherwise change the coverage of the rect
94 */
95 bool SkCanvas::wouldOverwriteEntireSurface(const SkRect* rect, const SkPaint* paint,
96 SkEnumBitMask<PredrawFlags> flags) const {
97 // Convert flags to a ShaderOverrideOpacity enum
98 auto overrideOpacity = (flags & PredrawFlags::kOpaqueShaderOverride) ?
99 SkPaintPriv::kOpaque_ShaderOverrideOpacity :
100 (flags & PredrawFlags::kNonOpaqueShaderOverride) ?
101 SkPaintPriv::kNotOpaque_ShaderOverrideOpacity :
102 SkPaintPriv::kNone_ShaderOverrideOpacity;
103
104 const SkISize size = this->getBaseLayerSize();
105 const SkRect bounds = SkRect::MakeIWH(size.width(), size.height());
106
107 // if we're clipped at all, we can't overwrite the entire surface
108 {
109 const SkDevice* root = this->rootDevice();
110 const SkDevice* top = this->topDevice();
111 if (root != top) {
112 return false; // we're in a saveLayer, so conservatively don't assume we'll overwrite
113 }
114 if (!root->isClipWideOpen()) {
115 return false;
116 }
117 }
118
119 if (rect) {
120 if (!this->getTotalMatrix().isScaleTranslate()) {
121 return false; // conservative
122 }
123
124 SkRect devRect;
125 this->getTotalMatrix().mapRectScaleTranslate(&devRect, *rect);
126 if (!devRect.contains(bounds)) {
127 return false;
128 }
129 }
130
131 if (paint) {
132 SkPaint::Style paintStyle = paint->getStyle();
133 if (!(paintStyle == SkPaint::kFill_Style ||
134 paintStyle == SkPaint::kStrokeAndFill_Style)) {
135 return false;
136 }
137 if (paint->getMaskFilter() || paint->getPathEffect() || paint->getImageFilter()) {
138 return false; // conservative
139 }
140 }
141 return SkPaintPriv::Overwrites(paint, overrideOpacity);
142 }
143
144 ///////////////////////////////////////////////////////////////////////////////////////////////////
145
predrawNotify(bool willOverwritesEntireSurface)146 bool SkCanvas::predrawNotify(bool willOverwritesEntireSurface) {
147 if (fSurfaceBase) {
148 if (!fSurfaceBase->aboutToDraw(willOverwritesEntireSurface
149 ? SkSurface::kDiscard_ContentChangeMode
150 : SkSurface::kRetain_ContentChangeMode)) {
151 return false;
152 }
153 }
154 return true;
155 }
156
predrawNotify(const SkRect * rect,const SkPaint * paint,SkEnumBitMask<PredrawFlags> flags)157 bool SkCanvas::predrawNotify(const SkRect* rect, const SkPaint* paint,
158 SkEnumBitMask<PredrawFlags> flags) {
159 if (fSurfaceBase) {
160 SkSurface::ContentChangeMode mode = SkSurface::kRetain_ContentChangeMode;
161 // Since willOverwriteAllPixels() may not be complete free to call, we only do so if
162 // there is an outstanding snapshot, since w/o that, there will be no copy-on-write
163 // and therefore we don't care which mode we're in.
164 //
165 if (fSurfaceBase->outstandingImageSnapshot()) {
166 if (this->wouldOverwriteEntireSurface(rect, paint, flags)) {
167 mode = SkSurface::kDiscard_ContentChangeMode;
168 }
169 }
170 if (!fSurfaceBase->aboutToDraw(mode)) {
171 return false;
172 }
173 }
174 return true;
175 }
176
177 ///////////////////////////////////////////////////////////////////////////////
178
Layer(sk_sp<SkDevice> device,FilterSpan imageFilters,const SkPaint & paint,bool isCoverage,bool includesPadding)179 SkCanvas::Layer::Layer(sk_sp<SkDevice> device,
180 FilterSpan imageFilters,
181 const SkPaint& paint,
182 bool isCoverage,
183 bool includesPadding)
184 : fDevice(std::move(device))
185 , fImageFilters(imageFilters.data(), imageFilters.size())
186 , fPaint(paint)
187 , fIsCoverage(isCoverage)
188 , fDiscard(false)
189 , fIncludesPadding(includesPadding) {
190 SkASSERT(fDevice);
191 // Any image filter should have been pulled out and stored in 'imageFilter' so that 'paint'
192 // can be used as-is to draw the result of the filter to the dst device.
193 SkASSERT(!fPaint.getImageFilter());
194 }
195
BackImage(sk_sp<SkSpecialImage> img,SkIPoint loc)196 SkCanvas::BackImage::BackImage(sk_sp<SkSpecialImage> img, SkIPoint loc)
197 :fImage(img), fLoc(loc) {}
198 SkCanvas::BackImage::BackImage(const BackImage&) = default;
199 SkCanvas::BackImage::BackImage(BackImage&&) = default;
200 SkCanvas::BackImage& SkCanvas::BackImage::operator=(const BackImage&) = default;
201 SkCanvas::BackImage::~BackImage() = default;
202
MCRec(SkDevice * device)203 SkCanvas::MCRec::MCRec(SkDevice* device) : fDevice(device) {
204 SkASSERT(fDevice);
205 }
206
MCRec(const MCRec * prev)207 SkCanvas::MCRec::MCRec(const MCRec* prev) : fDevice(prev->fDevice), fMatrix(prev->fMatrix) {
208 SkASSERT(fDevice);
209 }
210
~MCRec()211 SkCanvas::MCRec::~MCRec() {}
212
newLayer(sk_sp<SkDevice> layerDevice,FilterSpan filters,const SkPaint & restorePaint,bool layerIsCoverage,bool includesPadding)213 void SkCanvas::MCRec::newLayer(sk_sp<SkDevice> layerDevice,
214 FilterSpan filters,
215 const SkPaint& restorePaint,
216 bool layerIsCoverage,
217 bool includesPadding) {
218 SkASSERT(!fBackImage);
219 fLayer = std::make_unique<Layer>(std::move(layerDevice),
220 filters,
221 restorePaint,
222 layerIsCoverage,
223 includesPadding);
224 fDevice = fLayer->fDevice.get();
225 }
226
reset(SkDevice * device)227 void SkCanvas::MCRec::reset(SkDevice* device) {
228 SkASSERT(!fLayer);
229 SkASSERT(device);
230 SkASSERT(fDeferredSaveCount == 0);
231 fDevice = device;
232 fMatrix.setIdentity();
233 }
234
235 class SkCanvas::AutoUpdateQRBounds {
236 public:
AutoUpdateQRBounds(SkCanvas * canvas)237 explicit AutoUpdateQRBounds(SkCanvas* canvas) : fCanvas(canvas) {
238 // pre-condition, fQuickRejectBounds and other state should be valid before anything
239 // modifies the device's clip.
240 fCanvas->validateClip();
241 }
~AutoUpdateQRBounds()242 ~AutoUpdateQRBounds() {
243 fCanvas->fQuickRejectBounds = fCanvas->computeDeviceClipBounds();
244 // post-condition, we should remain valid after re-computing the bounds
245 fCanvas->validateClip();
246 }
247
248 private:
249 SkCanvas* fCanvas;
250
251 AutoUpdateQRBounds(AutoUpdateQRBounds&&) = delete;
252 AutoUpdateQRBounds(const AutoUpdateQRBounds&) = delete;
253 AutoUpdateQRBounds& operator=(AutoUpdateQRBounds&&) = delete;
254 AutoUpdateQRBounds& operator=(const AutoUpdateQRBounds&) = delete;
255 };
256
257 /////////////////////////////////////////////////////////////////////////////
258
aboutToDraw(const SkPaint & paint,const SkRect * rawBounds,SkEnumBitMask<PredrawFlags> flags)259 std::optional<AutoLayerForImageFilter> SkCanvas::aboutToDraw(
260 const SkPaint& paint,
261 const SkRect* rawBounds,
262 SkEnumBitMask<PredrawFlags> flags) {
263 if (flags & PredrawFlags::kCheckForOverwrite) {
264 if (!this->predrawNotify(rawBounds, &paint, flags)) {
265 return std::nullopt;
266 }
267 } else {
268 if (!this->predrawNotify()) {
269 return std::nullopt;
270 }
271 }
272
273 // TODO: Eventually all devices will use this code path and this will just test 'flags'.
274 const bool skipMaskFilterLayer = (flags & PredrawFlags::kSkipMaskFilterAutoLayer) ||
275 !this->topDevice()->useDrawCoverageMaskForMaskFilters();
276 return std::optional<AutoLayerForImageFilter>(
277 std::in_place, this, paint, rawBounds, skipMaskFilterLayer);
278 }
279
aboutToDraw(const SkPaint & paint,const SkRect * rawBounds)280 std::optional<AutoLayerForImageFilter> SkCanvas::aboutToDraw(
281 const SkPaint& paint,
282 const SkRect* rawBounds) {
283 return this->aboutToDraw(paint, rawBounds, PredrawFlags::kNone);
284 }
285
286 ////////////////////////////////////////////////////////////////////////////
287
resetForNextPicture(const SkIRect & bounds)288 void SkCanvas::resetForNextPicture(const SkIRect& bounds) {
289 this->restoreToCount(1);
290
291 // We're peering through a lot of structs here. Only at this scope do we know that the device
292 // is a SkNoPixelsDevice.
293 SkASSERT(fRootDevice->isNoPixelsDevice());
294 SkNoPixelsDevice* asNoPixelsDevice = static_cast<SkNoPixelsDevice*>(fRootDevice.get());
295 if (!asNoPixelsDevice->resetForNextPicture(bounds)) {
296 fRootDevice = sk_make_sp<SkNoPixelsDevice>(bounds,
297 fRootDevice->surfaceProps(),
298 fRootDevice->imageInfo().refColorSpace());
299 }
300
301 fMCRec->reset(fRootDevice.get());
302 fQuickRejectBounds = this->computeDeviceClipBounds();
303 }
304
init(sk_sp<SkDevice> device)305 void SkCanvas::init(sk_sp<SkDevice> device) {
306 if (!device) {
307 device = sk_make_sp<SkNoPixelsDevice>(SkIRect::MakeEmpty(), fProps);
308 }
309
310 // From this point on, SkCanvas will always have a device
311 SkASSERT(device);
312
313 fSaveCount = 1;
314 fMCRec = new (fMCStack.push_back()) MCRec(device.get());
315
316 // The root device and the canvas should always have the same pixel geometry
317 SkASSERT(fProps.pixelGeometry() == device->surfaceProps().pixelGeometry());
318
319 fSurfaceBase = nullptr;
320 fRootDevice = std::move(device);
321 fScratchGlyphRunBuilder = std::make_unique<sktext::GlyphRunBuilder>();
322 fQuickRejectBounds = this->computeDeviceClipBounds();
323 }
324
SkCanvas()325 SkCanvas::SkCanvas() : fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage)) {
326 this->init(nullptr);
327 }
328
SkCanvas(int width,int height,const SkSurfaceProps * props)329 SkCanvas::SkCanvas(int width, int height, const SkSurfaceProps* props)
330 : fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
331 , fProps(SkSurfacePropsCopyOrDefault(props)) {
332 this->init(sk_make_sp<SkNoPixelsDevice>(
333 SkIRect::MakeWH(std::max(width, 0), std::max(height, 0)), fProps));
334 }
335
SkCanvas(const SkIRect & bounds)336 SkCanvas::SkCanvas(const SkIRect& bounds)
337 : fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage)) {
338 SkIRect r = bounds.isEmpty() ? SkIRect::MakeEmpty() : bounds;
339 this->init(sk_make_sp<SkNoPixelsDevice>(r, fProps));
340 }
341
SkCanvas(sk_sp<SkDevice> device)342 SkCanvas::SkCanvas(sk_sp<SkDevice> device)
343 : fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
344 , fProps(device->surfaceProps()) {
345 this->init(std::move(device));
346 }
347
~SkCanvas()348 SkCanvas::~SkCanvas() {
349 // Mark all pending layers to be discarded during restore (rather than drawn)
350 SkDeque::Iter iter(fMCStack, SkDeque::Iter::kFront_IterStart);
351 for (;;) {
352 MCRec* rec = (MCRec*)iter.next();
353 if (!rec) {
354 break;
355 }
356 if (rec->fLayer) {
357 rec->fLayer->fDiscard = true;
358 }
359 }
360
361 // free up the contents of our deque
362 this->restoreToCount(1); // restore everything but the last
363 this->internalRestore(); // restore the last, since we're going away
364 }
365
getSurface() const366 SkSurface* SkCanvas::getSurface() const {
367 return fSurfaceBase;
368 }
369
getBaseLayerSize() const370 SkISize SkCanvas::getBaseLayerSize() const {
371 return this->rootDevice()->imageInfo().dimensions();
372 }
373
topDevice() const374 SkDevice* SkCanvas::topDevice() const {
375 SkASSERT(fMCRec->fDevice);
376 return fMCRec->fDevice;
377 }
378
readPixels(const SkPixmap & pm,int x,int y)379 bool SkCanvas::readPixels(const SkPixmap& pm, int x, int y) {
380 return pm.addr() && this->rootDevice()->readPixels(pm, x, y);
381 }
382
readPixels(const SkImageInfo & dstInfo,void * dstP,size_t rowBytes,int x,int y)383 bool SkCanvas::readPixels(const SkImageInfo& dstInfo, void* dstP, size_t rowBytes, int x, int y) {
384 return this->readPixels({ dstInfo, dstP, rowBytes}, x, y);
385 }
386
readPixels(const SkBitmap & bm,int x,int y)387 bool SkCanvas::readPixels(const SkBitmap& bm, int x, int y) {
388 SkPixmap pm;
389 return bm.peekPixels(&pm) && this->readPixels(pm, x, y);
390 }
391
writePixels(const SkBitmap & bitmap,int x,int y)392 bool SkCanvas::writePixels(const SkBitmap& bitmap, int x, int y) {
393 SkPixmap pm;
394 if (bitmap.peekPixels(&pm)) {
395 return this->writePixels(pm.info(), pm.addr(), pm.rowBytes(), x, y);
396 }
397 return false;
398 }
399
writePixels(const SkImageInfo & srcInfo,const void * pixels,size_t rowBytes,int x,int y)400 bool SkCanvas::writePixels(const SkImageInfo& srcInfo, const void* pixels, size_t rowBytes,
401 int x, int y) {
402 SkDevice* device = this->rootDevice();
403
404 // This check gives us an early out and prevents generation ID churn on the surface.
405 // This is purely optional: it is a subset of the checks performed by SkWritePixelsRec.
406 SkIRect srcRect = SkIRect::MakeXYWH(x, y, srcInfo.width(), srcInfo.height());
407 if (!srcRect.intersect({0, 0, device->width(), device->height()})) {
408 return false;
409 }
410
411 // Tell our owning surface to bump its generation ID.
412 const bool completeOverwrite = srcRect.size() == device->imageInfo().dimensions();
413 if (!this->predrawNotify(completeOverwrite)) {
414 return false;
415 }
416
417 // This can still fail, most notably in the case of a invalid color type or alpha type
418 // conversion. We could pull those checks into this function and avoid the unnecessary
419 // generation ID bump. But then we would be performing those checks twice, since they
420 // are also necessary at the bitmap/pixmap entry points.
421 return device->writePixels({srcInfo, pixels, rowBytes}, x, y);
422 }
423
424 //////////////////////////////////////////////////////////////////////////////
425
checkForDeferredSave()426 void SkCanvas::checkForDeferredSave() {
427 if (fMCRec->fDeferredSaveCount > 0) {
428 this->doSave();
429 }
430 }
431
getSaveCount() const432 int SkCanvas::getSaveCount() const {
433 #ifdef SK_DEBUG
434 int count = 0;
435 SkDeque::Iter iter(fMCStack, SkDeque::Iter::kFront_IterStart);
436 for (;;) {
437 const MCRec* rec = (const MCRec*)iter.next();
438 if (!rec) {
439 break;
440 }
441 count += 1 + rec->fDeferredSaveCount;
442 }
443 SkASSERT(count == fSaveCount);
444 #endif
445 return fSaveCount;
446 }
447
save()448 int SkCanvas::save() {
449 fSaveCount += 1;
450 fMCRec->fDeferredSaveCount += 1;
451 return this->getSaveCount() - 1; // return our prev value
452 }
453
doSave()454 void SkCanvas::doSave() {
455 this->willSave();
456
457 SkASSERT(fMCRec->fDeferredSaveCount > 0);
458 fMCRec->fDeferredSaveCount -= 1;
459 this->internalSave();
460 }
461
restore()462 void SkCanvas::restore() {
463 if (fMCRec->fDeferredSaveCount > 0) {
464 SkASSERT(fSaveCount > 1);
465 fSaveCount -= 1;
466 fMCRec->fDeferredSaveCount -= 1;
467 } else {
468 // check for underflow
469 if (fMCStack.count() > 1) {
470 this->willRestore();
471 SkASSERT(fSaveCount > 1);
472 fSaveCount -= 1;
473 this->internalRestore();
474 this->didRestore();
475 }
476 }
477 }
478
restoreToCount(int count)479 void SkCanvas::restoreToCount(int count) {
480 // safety check
481 if (count < 1) {
482 count = 1;
483 }
484
485 int n = this->getSaveCount() - count;
486 for (int i = 0; i < n; ++i) {
487 this->restore();
488 }
489 }
490
internalSave()491 void SkCanvas::internalSave() {
492 fMCRec = new (fMCStack.push_back()) MCRec(fMCRec);
493
494 this->topDevice()->pushClipStack();
495 }
496
saveLayer(const SkRect * bounds,const SkPaint * paint)497 int SkCanvas::saveLayer(const SkRect* bounds, const SkPaint* paint) {
498 return this->saveLayer(SaveLayerRec(bounds, paint, 0));
499 }
500
saveLayer(const SaveLayerRec & rec)501 int SkCanvas::saveLayer(const SaveLayerRec& rec) {
502 TRACE_EVENT0("skia", TRACE_FUNC);
503 if (rec.fPaint && rec.fPaint->nothingToDraw()) {
504 // no need for the layer (or any of the draws until the matching restore()
505 this->save();
506 this->clipRect({0,0,0,0});
507 } else {
508 SaveLayerStrategy strategy = this->getSaveLayerStrategy(rec);
509 fSaveCount += 1;
510 this->internalSaveLayer(rec, strategy);
511 }
512 return this->getSaveCount() - 1;
513 }
514
only_axis_aligned_saveBehind(const SkRect * bounds)515 int SkCanvas::only_axis_aligned_saveBehind(const SkRect* bounds) {
516 if (bounds && !this->getLocalClipBounds().intersects(*bounds)) {
517 // Assuming clips never expand, if the request bounds is outside of the current clip
518 // there is no need to copy/restore the area, so just devolve back to a regular save.
519 this->save();
520 } else {
521 bool doTheWork = this->onDoSaveBehind(bounds);
522 fSaveCount += 1;
523 this->internalSave();
524 if (doTheWork) {
525 this->internalSaveBehind(bounds);
526 }
527 }
528 return this->getSaveCount() - 1;
529 }
530
531 // Helper function to compute the center reference point used for scale decomposition under
532 // non-linear transformations.
compute_decomposition_center(const SkMatrix & dstToLocal,std::optional<skif::ParameterSpace<SkRect>> contentBounds,const skif::DeviceSpace<SkIRect> & targetOutput)533 static skif::ParameterSpace<SkPoint> compute_decomposition_center(
534 const SkMatrix& dstToLocal,
535 std::optional<skif::ParameterSpace<SkRect>> contentBounds,
536 const skif::DeviceSpace<SkIRect>& targetOutput) {
537 // Will use the inverse and center of the device bounds if the content bounds aren't provided.
538 SkRect rect = contentBounds ? SkRect(*contentBounds) : SkRect::Make(SkIRect(targetOutput));
539 SkPoint center = {rect.centerX(), rect.centerY()};
540 if (!contentBounds) {
541 // Theoretically, the inverse transform could put center's homogeneous coord behind W = 0,
542 // but that case is handled automatically in Mapping::decomposeCTM later.
543 dstToLocal.mapPoints(¢er, 1);
544 }
545
546 return skif::ParameterSpace<SkPoint>(center);
547 }
548
549 // Helper when we need to upgrade a single filter to a FilterSpan
550 struct FilterToSpan {
FilterToSpanFilterToSpan551 FilterToSpan(const SkImageFilter* filter) : fFilter(sk_ref_sp(filter)) {}
552
operator SkCanvas::FilterSpanFilterToSpan553 operator SkCanvas::FilterSpan() {
554 return fFilter ? SkCanvas::FilterSpan{&fFilter, 1} : SkCanvas::FilterSpan{};
555 }
556
557 sk_sp<SkImageFilter> fFilter;
558 };
559
560 // Compute suitable transformations and layer bounds for a new layer that will be used as the source
561 // input into 'filter' before being drawn into 'dst' via the returned skif::Mapping.
562 // Null filters are permitted and act as the identity. The returned mapping will be compatible with
563 // the image filter.
564 //
565 // An empty optional is returned if the layer mapping and bounds couldn't be determined, in which
566 // case the layer should be skipped. An instantiated optional can have an empty layer bounds rect
567 // if the image filter doesn't require an input image to produce a valid output.
568 static std::optional<std::pair<skif::Mapping, skif::LayerSpace<SkIRect>>>
get_layer_mapping_and_bounds(SkCanvas::FilterSpan filters,const SkMatrix & localToDst,const skif::DeviceSpace<SkIRect> & targetOutput,std::optional<skif::ParameterSpace<SkRect>> contentBounds={},SkScalar scaleFactor=1.0f)569 get_layer_mapping_and_bounds(
570 SkCanvas::FilterSpan filters,
571 const SkMatrix& localToDst,
572 const skif::DeviceSpace<SkIRect>& targetOutput,
573 std::optional<skif::ParameterSpace<SkRect>> contentBounds = {},
574 SkScalar scaleFactor = 1.0f) {
575 SkMatrix dstToLocal;
576 if (!localToDst.isFinite() ||
577 !localToDst.invert(&dstToLocal)) {
578 return {};
579 }
580
581 skif::ParameterSpace<SkPoint> center =
582 compute_decomposition_center(dstToLocal, contentBounds, targetOutput);
583
584 // Determine initial mapping and a reasonable maximum dimension to prevent layer-to-device
585 // transforms with perspective and skew from triggering excessive buffer allocations.
586 skif::Mapping mapping;
587 skif::MatrixCapability capability = skif::MatrixCapability::kComplex;
588 for (const sk_sp<SkImageFilter>& filter : filters) {
589 if (filter) {
590 capability = std::min(capability, as_IFB(filter)->getCTMCapability());
591 }
592 }
593 if (!mapping.decomposeCTM(localToDst, capability, center)) {
594 return {};
595 }
596 // Push scale factor into layer matrix and device matrix (net no change, but the layer will have
597 // its resolution adjusted in comparison to the final device).
598 if (scaleFactor != 1.0f &&
599 !mapping.adjustLayerSpace(SkMatrix::Scale(scaleFactor, scaleFactor))) {
600 return {};
601 }
602
603 // Perspective and skew could exceed this since mapping.deviceToLayer(targetOutput) is
604 // theoretically unbounded under those conditions. Under a 45 degree rotation, a layer needs to
605 // be 2X larger per side of the prior device in order to fully cover it. We use the max of that
606 // and 2048 for a reasonable upper limit (this allows small layers under extreme transforms to
607 // use more relative resolution than a larger layer).
608 static const int kMinDimThreshold = 2048;
609 int maxLayerDim = std::max(Sk64_pin_to_s32(2 * std::max(SkIRect(targetOutput).width64(),
610 SkIRect(targetOutput).height64())),
611 kMinDimThreshold);
612
613 auto baseLayerBounds = mapping.deviceToLayer(targetOutput);
614 if (contentBounds) {
615 // For better or for worse, user bounds currently act as a hard clip on the layer's
616 // extent (i.e., they implement the CSS filter-effects 'filter region' feature).
617 skif::LayerSpace<SkIRect> knownBounds = mapping.paramToLayer(*contentBounds).roundOut();
618 if (!baseLayerBounds.intersect(knownBounds)) {
619 baseLayerBounds = skif::LayerSpace<SkIRect>::Empty();
620 }
621 }
622
623 skif::LayerSpace<SkIRect> layerBounds;
624 if (!filters.empty()) {
__anone5c83ba80102(int i) 625 layerBounds = skif::LayerSpace<SkIRect>::Union(filters.size(), [&](int i) {
626 return filters[i] ? as_IFB(filters[i])
627 ->getInputBounds(mapping, targetOutput, contentBounds)
628 : baseLayerBounds;
629 });
630 // When a filter is involved, the layer size may be larger than the default maxLayerDim due
631 // to required inputs for filters (e.g. a displacement map with a large radius).
632 if (layerBounds.width() > maxLayerDim || layerBounds.height() > maxLayerDim) {
633 skif::Mapping idealMapping{mapping.layerMatrix()};
634 for (const sk_sp<SkImageFilter>& filter : filters) {
635 if (filter) {
636 auto idealLayerBounds = as_IFB(filter)->getInputBounds(
637 idealMapping, targetOutput, contentBounds);
638 maxLayerDim = std::max(std::max(idealLayerBounds.width(),
639 idealLayerBounds.height()),
640 maxLayerDim);
641 }
642 }
643 }
644 } else {
645 if (baseLayerBounds.isEmpty()) {
646 return {};
647 }
648 layerBounds = baseLayerBounds;
649 }
650
651 if (layerBounds.width() > maxLayerDim || layerBounds.height() > maxLayerDim) {
652 skif::LayerSpace<SkIRect> newLayerBounds(
653 SkIRect::MakeWH(std::min(layerBounds.width(), maxLayerDim),
654 std::min(layerBounds.height(), maxLayerDim)));
655 SkMatrix adjust = SkMatrix::MakeRectToRect(SkRect::Make(SkIRect(layerBounds)),
656 SkRect::Make(SkIRect(newLayerBounds)),
657 SkMatrix::kFill_ScaleToFit);
658 if (!mapping.adjustLayerSpace(adjust)) {
659 return {};
660 } else {
661 layerBounds = newLayerBounds;
662 }
663 }
664
665 return std::make_pair(mapping, layerBounds);
666 }
667
668 // Ideally image filters operate in the dst color type, but if there is insufficient alpha bits
669 // we move some bits from color channels into the alpha channel since that can greatly improve
670 // the quality of blurs and other filters.
image_filter_color_type(const SkColorInfo & dstInfo)671 static SkColorType image_filter_color_type(const SkColorInfo& dstInfo) {
672 if (dstInfo.bytesPerPixel() <= 4 &&
673 dstInfo.colorType() != kRGBA_8888_SkColorType &&
674 dstInfo.colorType() != kBGRA_8888_SkColorType) {
675 // "Upgrade" A8, G8, 565, 4444, 1010102, 101010x, and 888x to 8888
676 return kN32_SkColorType;
677 } else {
678 return dstInfo.colorType();
679 }
680 }
681
apply_alpha_and_colorfilter(const skif::Context & ctx,const skif::FilterResult & image,const SkPaint & paint)682 static skif::FilterResult apply_alpha_and_colorfilter(const skif::Context& ctx,
683 const skif::FilterResult& image,
684 const SkPaint& paint) {
685 // The only effects that apply to layers (other than the SkImageFilter that made this image in
686 // the first place) are transparency and color filters.
687 skif::FilterResult result = image;
688 if (paint.getAlphaf() < 1.f) {
689 result = result.applyColorFilter(ctx, SkColorFilters::Blend(paint.getColor4f(),
690 /*colorSpace=*/nullptr,
691 SkBlendMode::kDstIn));
692 }
693 if (paint.getColorFilter()) {
694 result = result.applyColorFilter(ctx, paint.refColorFilter());
695 }
696 return result;
697 }
698
internalDrawDeviceWithFilter(SkDevice * src,SkDevice * dst,FilterSpan filters,const SkPaint & paint,DeviceCompatibleWithFilter compat,const SkColorInfo & filterColorInfo,SkScalar scaleFactor,SkTileMode srcTileMode,bool srcIsCoverageLayer)699 void SkCanvas::internalDrawDeviceWithFilter(SkDevice* src,
700 SkDevice* dst,
701 FilterSpan filters,
702 const SkPaint& paint,
703 DeviceCompatibleWithFilter compat,
704 const SkColorInfo& filterColorInfo,
705 SkScalar scaleFactor,
706 SkTileMode srcTileMode,
707 bool srcIsCoverageLayer) {
708 // The dst is always required, the src can be null if 'filter' is non-null and does not require
709 // a source image. For regular filters, 'src' is the layer and 'dst' is the parent device. For
710 // backdrop filters, 'src' is the parent device and 'dst' is the layer.
711 SkASSERT(dst);
712
713 sk_sp<SkColorSpace> filterColorSpace = filterColorInfo.refColorSpace();
714
715 const SkColorType filterColorType =
716 srcIsCoverageLayer ? kAlpha_8_SkColorType : image_filter_color_type(filterColorInfo);
717
718 // 'filter' sees the src device's buffer as the implicit input image, and processes the image
719 // in this device space (referred to as the "layer" space). However, the filter
720 // parameters need to respect the current matrix, which is not necessarily the local matrix that
721 // was set on 'src' (e.g. because we've popped src off the stack already).
722 // TODO (michaelludwig): Stay in SkM44 once skif::Mapping supports SkM44 instead of SkMatrix.
723 SkMatrix localToSrc = src ? (src->globalToDevice() * fMCRec->fMatrix).asM33() : SkMatrix::I();
724 SkISize srcDims = src ? src->imageInfo().dimensions() : SkISize::Make(0, 0);
725
726 // Whether or not we need to make a transformed tmp image from 'src', and what that transform is
727 skif::LayerSpace<SkMatrix> srcToLayer;
728
729 skif::Mapping mapping;
730 skif::LayerSpace<SkIRect> requiredInput;
731 skif::DeviceSpace<SkIRect> outputBounds{dst->devClipBounds()};
732 if (compat != DeviceCompatibleWithFilter::kUnknown) {
733 // Just use the relative transform from src to dst and the src's whole image, since
734 // internalSaveLayer should have already determined what was necessary. We explicitly
735 // construct the inverse (dst->src) to avoid the case where src's and dst's coord transforms
736 // were individually invertible by SkM44::invert() but their product is considered not
737 // invertible by SkMatrix::invert(). When this happens the matrices are already poorly
738 // conditioned so getRelativeTransform() gives us something reasonable.
739 SkASSERT(src);
740 SkASSERT(scaleFactor == 1.0f);
741 SkASSERT(!srcDims.isEmpty());
742
743 mapping = skif::Mapping(src->getRelativeTransform(*dst),
744 dst->getRelativeTransform(*src),
745 localToSrc);
746 requiredInput = skif::LayerSpace<SkIRect>(SkIRect::MakeSize(srcDims));
747 srcToLayer = skif::LayerSpace<SkMatrix>(SkMatrix::I());
748 } else {
749 // Compute the image filter mapping by decomposing the local->device matrix of dst and
750 // re-determining the required input.
751 auto mappingAndBounds = get_layer_mapping_and_bounds(
752 filters, dst->localToDevice(), outputBounds, {}, SkTPin(scaleFactor, 0.f, 1.f));
753 if (!mappingAndBounds) {
754 return;
755 }
756
757 std::tie(mapping, requiredInput) = *mappingAndBounds;
758 if (src) {
759 if (!requiredInput.isEmpty()) {
760 // The above mapping transforms from local to dst's device space, where the layer
761 // space represents the intermediate buffer. Now we need to determine the transform
762 // from src to intermediate to prepare the input to the filter.
763 SkMatrix srcToLocal;
764 if (!localToSrc.invert(&srcToLocal)) {
765 return;
766 }
767 srcToLayer = skif::LayerSpace<SkMatrix>(SkMatrix::Concat(mapping.layerMatrix(),
768 srcToLocal));
769 } // Else no input is needed which can happen if a backdrop filter that doesn't use src
770 } else {
771 // Trust the caller that no input was required, but keep the calculated mapping
772 requiredInput = skif::LayerSpace<SkIRect>::Empty();
773 }
774 }
775
776 // Start out with an empty source image, to be replaced with the snapped 'src' device.
777 auto backend = dst->createImageFilteringBackend(src ? src->surfaceProps() : dst->surfaceProps(),
778 filterColorType);
779 skif::Stats stats;
780 skif::Context ctx{std::move(backend),
781 mapping,
782 requiredInput,
783 skif::FilterResult{},
784 filterColorSpace.get(),
785 &stats};
786
787 skif::FilterResult source;
788 if (src && !requiredInput.isEmpty()) {
789 skif::LayerSpace<SkIRect> srcSubset;
790 if (!srcToLayer.inverseMapRect(requiredInput, &srcSubset)) {
791 return;
792 }
793
794 // Include the layer in the offscreen count
795 ctx.markNewSurface();
796
797 auto availSrc = skif::LayerSpace<SkIRect>(src->size()).relevantSubset(
798 srcSubset, srcTileMode);
799
800 if (SkMatrix(srcToLayer).isScaleTranslate()) {
801 // Apply the srcToLayer transformation directly while snapping an image from the src
802 // device. Calculate the subset of requiredInput that corresponds to srcSubset that was
803 // restricted to the actual src dimensions.
804 auto requiredSubset = srcToLayer.mapRect(availSrc);
805 if (requiredSubset.width() == availSrc.width() &&
806 requiredSubset.height() == availSrc.height()) {
807 // Unlike snapSpecialScaled(), snapSpecial() can avoid a copy when the underlying
808 // representation permits it.
809 source = {src->snapSpecial(SkIRect(availSrc)), requiredSubset.topLeft()};
810 } else {
811 SkASSERT(compat == DeviceCompatibleWithFilter::kUnknown);
812 source = {src->snapSpecialScaled(SkIRect(availSrc),
813 SkISize(requiredSubset.size())),
814 requiredSubset.topLeft()};
815 ctx.markNewSurface();
816 }
817 }
818
819 if (compat == DeviceCompatibleWithFilter::kYesWithPadding) {
820 // Padding was added to the source image when the 'src' SkDevice was created, so inset
821 // to allow bounds tracking to skip shader-based tiling when possible.
822 SkASSERT(!filters.empty());
823 source = source.insetForSaveLayer();
824 } else if (compat == DeviceCompatibleWithFilter::kYes) {
825 // Do nothing, leave `source` as-is; FilterResult will automatically augment the image
826 // sampling as needed to be visually equivalent to the more optimal kYesWithPadding case
827 } else if (source) {
828 // A backdrop filter that succeeded in snapSpecial() or snapSpecialScaled(), but since
829 // the 'src' device wasn't prepared with 'requiredInput' in mind, add clamping.
830 source = source.applyCrop(ctx, source.layerBounds(), srcTileMode);
831 } else if (!requiredInput.isEmpty()) {
832 // Otherwise snapSpecialScaled() failed or the transform was complex, so snap the source
833 // image at its original resolution and then apply srcToLayer to map to the effective
834 // layer coordinate space.
835 source = {src->snapSpecial(SkIRect(availSrc)), availSrc.topLeft()};
836 // We adjust the desired output of the applyCrop() because ctx was original set to
837 // fulfill 'requiredInput', which is valid *after* we apply srcToLayer. Use the original
838 // 'srcSubset' for the desired output so that the tilemode applied to the available
839 // subset is not discarded as a no-op.
840 source = source.applyCrop(ctx.withNewDesiredOutput(srcSubset),
841 source.layerBounds(),
842 srcTileMode)
843 .applyTransform(ctx, srcToLayer, SkFilterMode::kLinear);
844 }
845 } // else leave 'source' as the empty image
846
847 // Evaluate the image filter, with a context pointing to the source snapped from 'src' and
848 // possibly transformed into the intermediate layer coordinate space.
849 ctx = ctx.withNewDesiredOutput(mapping.deviceToLayer(outputBounds))
850 .withNewSource(source);
851
852 // Here, we allow a single-element FilterSpan with a null entry, to simplify the loop:
853 sk_sp<SkImageFilter> nullFilter;
854 FilterSpan filtersOrNull = filters.empty() ? FilterSpan{&nullFilter, 1} : filters;
855
856 for (const sk_sp<SkImageFilter>& filter : filtersOrNull) {
857 auto result = filter ? as_IFB(filter)->filterImage(ctx) : source;
858
859 if (srcIsCoverageLayer) {
860 SkASSERT(dst->useDrawCoverageMaskForMaskFilters());
861 // TODO: Can FilterResult optimize this in any meaningful way if it still has to go
862 // through drawCoverageMask that requires an image (vs a coverage shader)?
863 auto [coverageMask, origin] = result.imageAndOffset(ctx);
864 if (coverageMask) {
865 SkMatrix deviceMatrixWithOffset = mapping.layerToDevice();
866 deviceMatrixWithOffset.preTranslate(origin.x(), origin.y());
867 dst->drawCoverageMask(
868 coverageMask.get(), deviceMatrixWithOffset, result.sampling(), paint);
869 }
870 } else {
871 result = apply_alpha_and_colorfilter(ctx, result, paint);
872 result.draw(ctx, dst, paint.getBlender());
873 }
874 }
875
876 stats.reportStats();
877 }
878
internalSaveLayer(const SaveLayerRec & rec,SaveLayerStrategy strategy,bool coverageOnly)879 void SkCanvas::internalSaveLayer(const SaveLayerRec& rec,
880 SaveLayerStrategy strategy,
881 bool coverageOnly) {
882 TRACE_EVENT0("skia", TRACE_FUNC);
883 // Do this before we create the layer. We don't call the public save() since that would invoke a
884 // possibly overridden virtual.
885 this->internalSave();
886
887 if (this->isClipEmpty()) {
888 // Early out if the layer wouldn't draw anything
889 return;
890 }
891
892 // Build up the paint for restoring the layer, taking only the pieces of rec.fPaint that are
893 // relevant. Filtering is automatically chosen in internalDrawDeviceWithFilter based on the
894 // device's coordinate space.
895 SkPaint restorePaint(rec.fPaint ? *rec.fPaint : SkPaint());
896 restorePaint.setStyle(SkPaint::kFill_Style); // a layer is filled out "infinitely"
897 restorePaint.setPathEffect(nullptr); // path effects are ignored for saved layers
898 restorePaint.setMaskFilter(nullptr); // mask filters are ignored for saved layers
899 restorePaint.setImageFilter(nullptr); // the image filter is held separately
900 // Smooth non-axis-aligned layer edges; this automatically downgrades to non-AA for aligned
901 // layer restores. This is done to match legacy behavior where the post-applied MatrixTransform
902 // bilerp also smoothed cropped edges. See skbug.com/11252
903 restorePaint.setAntiAlias(true);
904
905 sk_sp<SkImageFilter> paintFilter = rec.fPaint ? rec.fPaint->refImageFilter() : nullptr;
906 FilterSpan filters = paintFilter ? FilterSpan{&paintFilter, 1} : rec.fFilters;
907 if (filters.size() > kMaxFiltersPerLayer) {
908 filters = filters.first(kMaxFiltersPerLayer);
909 }
910 const SkColorFilter* cf = restorePaint.getColorFilter();
911 const SkBlender* blender = restorePaint.getBlender();
912
913 // When this is false, restoring the layer filled with unmodified prior contents should be
914 // identical to the prior contents, so we can restrict the layer even more than just the
915 // clip bounds.
916 bool filtersPriorDevice = rec.fBackdrop;
917 #if !defined(SK_LEGACY_INITWITHPREV_LAYER_SIZING)
918 // A regular filter applied to a layer initialized with prior contents is somewhat
919 // analogous to a backdrop filter so they are treated the same.
920 // TODO(b/314968012): Chrome needs to be updated to clip saveAlphaLayer bounds explicitly when
921 // it uses kInitWithPrevious and LCD text.
922 filtersPriorDevice |= ((rec.fSaveLayerFlags & kInitWithPrevious_SaveLayerFlag) &&
923 (!filters.empty() || cf || blender || restorePaint.getAlphaf() < 1.f));
924 #endif
925 // If the restorePaint has a transparency-affecting colorfilter or blender, the output is
926 // unbounded during restore(). `internalDrawDeviceWithFilter` automatically applies these
927 // effects. When there's no image filter, SkDevice::drawDevice is used, which does
928 // not apply effects beyond the layer's image so we mark `trivialRestore` as false too.
929 // TODO: drawDevice() could be updated to apply transparency-affecting effects to a content-
930 // clipped image, but this is the simplest solution when considering document-based SkDevices.
931 const bool drawDeviceMustFillClip = filters.empty() &&
932 ((cf && as_CFB(cf)->affectsTransparentBlack()) ||
933 (blender && as_BB(blender)->affectsTransparentBlack()));
934 const bool trivialRestore = !filtersPriorDevice && !drawDeviceMustFillClip;
935
936 // Size the new layer relative to the prior device, which may already be aligned for filters.
937 SkDevice* priorDevice = this->topDevice();
938 skif::Mapping newLayerMapping;
939 skif::LayerSpace<SkIRect> layerBounds;
940 skif::DeviceSpace<SkIRect> outputBounds{priorDevice->devClipBounds()};
941
942 std::optional<skif::ParameterSpace<SkRect>> contentBounds;
943 // Set the bounds hint if provided and there's no further effects on prior device content
944 if (rec.fBounds && trivialRestore) {
945 contentBounds = skif::ParameterSpace<SkRect>(*rec.fBounds);
946 }
947
948 auto mappingAndBounds = get_layer_mapping_and_bounds(
949 filters, priorDevice->localToDevice(), outputBounds, contentBounds);
950
951 auto abortLayer = [this]() {
952 // The filtered content would not draw anything, or the new device space has an invalid
953 // coordinate system, in which case we mark the current top device as empty so that nothing
954 // draws until the canvas is restored past this saveLayer.
955 AutoUpdateQRBounds aqr(this);
956 this->topDevice()->clipRect(SkRect::MakeEmpty(), SkClipOp::kIntersect, /* aa */ false);
957 };
958
959 if (!mappingAndBounds) {
960 abortLayer();
961 return;
962 }
963
964 std::tie(newLayerMapping, layerBounds) = *mappingAndBounds;
965
966 bool paddedLayer = false;
967 if (layerBounds.isEmpty()) {
968 // The image filter graph does not require any input, so we don't need to actually render
969 // a new layer for the source image. This could be because the image filter itself will not
970 // produce output, or that the filter DAG has no references to the dynamic source image.
971 // In this case it still has an output that we need to render, but do so now since there is
972 // no new layer pushed on the stack and the paired restore() will be a no-op.
973 if (!filters.empty() && !priorDevice->isNoPixelsDevice()) {
974 SkColorInfo filterColorInfo = priorDevice->imageInfo().colorInfo();
975 if (rec.fColorSpace) {
976 filterColorInfo = filterColorInfo.makeColorSpace(sk_ref_sp(rec.fColorSpace));
977 }
978 this->internalDrawDeviceWithFilter(/*src=*/nullptr, priorDevice, filters, restorePaint,
979 DeviceCompatibleWithFilter::kUnknown,
980 filterColorInfo);
981 }
982
983 // Regardless of if we drew the "restored" image filter or not, mark the layer as empty
984 // until the restore() since we don't care about any of its content.
985 abortLayer();
986 return;
987 } else {
988 // TODO(b/329700315): Once dithers can be anchored more flexibly, we can return to
989 // universally adding padding even for layers w/o filters. This change would simplify layer
990 // prep and restore logic and allow us to flexibly switch the sampling to linear if NN has
991 // issues on certain hardware.
992 if (!filters.empty()) {
993 // Add a buffer of padding so that image filtering can avoid accessing unitialized data
994 // and switch from shader-decal'ing to clamping.
995 auto paddedLayerBounds = layerBounds;
996 paddedLayerBounds.outset(skif::LayerSpace<SkISize>({1, 1}));
997 if (paddedLayerBounds.left() < layerBounds.left() &&
998 paddedLayerBounds.top() < layerBounds.top() &&
999 paddedLayerBounds.right() > layerBounds.right() &&
1000 paddedLayerBounds.bottom() > layerBounds.bottom()) {
1001 // The outset was not saturated to INT_MAX, so the transparent pixels can be
1002 // preserved.
1003 layerBounds = paddedLayerBounds;
1004 paddedLayer = true;
1005 }
1006 }
1007 }
1008
1009 sk_sp<SkDevice> newDevice;
1010 if (strategy == kFullLayer_SaveLayerStrategy) {
1011 SkASSERT(!layerBounds.isEmpty());
1012
1013 SkColorType layerColorType;
1014 if (coverageOnly) {
1015 layerColorType = kAlpha_8_SkColorType;
1016 } else {
1017 layerColorType = SkToBool(rec.fSaveLayerFlags & kF16ColorType)
1018 ? kRGBA_F16_SkColorType
1019 : image_filter_color_type(priorDevice->imageInfo().colorInfo());
1020 }
1021 SkImageInfo info =
1022 SkImageInfo::Make(layerBounds.width(),
1023 layerBounds.height(),
1024 layerColorType,
1025 kPremul_SkAlphaType,
1026 rec.fColorSpace ? sk_ref_sp(rec.fColorSpace)
1027 : priorDevice->imageInfo().refColorSpace());
1028
1029 SkPixelGeometry geo = rec.fSaveLayerFlags & kPreserveLCDText_SaveLayerFlag
1030 ? fProps.pixelGeometry()
1031 : kUnknown_SkPixelGeometry;
1032 const auto createInfo = SkDevice::CreateInfo(info, geo, fAllocator.get());
1033 // Use the original paint as a hint so that it includes the image filter
1034 newDevice = priorDevice->createDevice(createInfo, rec.fPaint);
1035 }
1036
1037 bool initBackdrop = (rec.fSaveLayerFlags & kInitWithPrevious_SaveLayerFlag) || rec.fBackdrop;
1038 if (!newDevice) {
1039 // Either we weren't meant to allocate a full layer, or the full layer creation failed.
1040 // Using an explicit NoPixelsDevice lets us reflect what the layer state would have been
1041 // on success (or kFull_LayerStrategy) while squashing draw calls that target something that
1042 // doesn't exist.
1043 newDevice = sk_make_sp<SkNoPixelsDevice>(SkIRect::MakeWH(layerBounds.width(),
1044 layerBounds.height()),
1045 fProps, this->imageInfo().refColorSpace());
1046 initBackdrop = false;
1047 }
1048
1049 // Clip while the device coordinate space is the identity so it's easy to define the rect that
1050 // excludes the added padding pixels. This ensures they remain cleared to transparent black.
1051 if (paddedLayer) {
1052 newDevice->clipRect(SkRect::Make(newDevice->devClipBounds().makeInset(1, 1)),
1053 SkClipOp::kIntersect, /*aa=*/false);
1054 }
1055
1056 // Configure device to match determined mapping for any image filters.
1057 // The setDeviceCoordinateSystem applies the prior device's global transform since
1058 // 'newLayerMapping' only defines the transforms between the two devices and it must be updated
1059 // to the global coordinate system.
1060 newDevice->setDeviceCoordinateSystem(
1061 priorDevice->deviceToGlobal() * SkM44(newLayerMapping.layerToDevice()),
1062 SkM44(newLayerMapping.deviceToLayer()) * priorDevice->globalToDevice(),
1063 SkM44(newLayerMapping.layerMatrix()),
1064 layerBounds.left(),
1065 layerBounds.top());
1066
1067 if (initBackdrop) {
1068 SkASSERT(!coverageOnly);
1069 SkPaint backdropPaint;
1070 FilterToSpan backdropAsSpan(rec.fBackdrop);
1071 // The new device was constructed to be compatible with 'filter', not necessarily
1072 // 'rec.fBackdrop', so allow DrawDeviceWithFilter to transform the prior device contents
1073 // if necessary to evaluate the backdrop filter. If no filters are involved, then the
1074 // devices differ by integer translations and are always compatible.
1075 bool scaleBackdrop = rec.fExperimentalBackdropScale != 1.0f;
1076 auto compat = (!filters.empty() || rec.fBackdrop || scaleBackdrop)
1077 ? DeviceCompatibleWithFilter::kUnknown : DeviceCompatibleWithFilter::kYes;
1078 // Using the color info of 'newDevice' is equivalent to using 'rec.fColorSpace'.
1079 this->internalDrawDeviceWithFilter(priorDevice, // src
1080 newDevice.get(), // dst
1081 backdropAsSpan,
1082 backdropPaint,
1083 compat,
1084 newDevice->imageInfo().colorInfo(),
1085 rec.fExperimentalBackdropScale,
1086 rec.fBackdropTileMode);
1087 }
1088
1089 fMCRec->newLayer(std::move(newDevice), filters, restorePaint, coverageOnly, paddedLayer);
1090 fQuickRejectBounds = this->computeDeviceClipBounds();
1091 }
1092
saveLayerAlphaf(const SkRect * bounds,float alpha)1093 int SkCanvas::saveLayerAlphaf(const SkRect* bounds, float alpha) {
1094 if (alpha >= 1.0f) {
1095 return this->saveLayer(bounds, nullptr);
1096 } else {
1097 SkPaint tmpPaint;
1098 tmpPaint.setAlphaf(alpha);
1099 return this->saveLayer(bounds, &tmpPaint);
1100 }
1101 }
1102
internalSaveBehind(const SkRect * localBounds)1103 void SkCanvas::internalSaveBehind(const SkRect* localBounds) {
1104 SkDevice* device = this->topDevice();
1105
1106 // Map the local bounds into the top device's coordinate space (this is not
1107 // necessarily the full global CTM transform).
1108 SkIRect devBounds;
1109 if (localBounds) {
1110 SkRect tmp;
1111 device->localToDevice().mapRect(&tmp, *localBounds);
1112 if (!devBounds.intersect(tmp.round(), device->devClipBounds())) {
1113 devBounds.setEmpty();
1114 }
1115 } else {
1116 devBounds = device->devClipBounds();
1117 }
1118 if (devBounds.isEmpty()) {
1119 return;
1120 }
1121
1122 // This is getting the special image from the current device, which is then drawn into (both by
1123 // a client, and the drawClippedToSaveBehind below). Since this is not saving a layer, with its
1124 // own device, we need to explicitly copy the back image contents so that its original content
1125 // is available when we splat it back later during restore.
1126 auto backImage = device->snapSpecial(devBounds, /* forceCopy= */ true);
1127 if (!backImage) {
1128 return;
1129 }
1130
1131 // we really need the save, so we can wack the fMCRec
1132 this->checkForDeferredSave();
1133
1134 fMCRec->fBackImage =
1135 std::make_unique<BackImage>(BackImage{std::move(backImage), devBounds.topLeft()});
1136
1137 SkPaint paint;
1138 paint.setBlendMode(SkBlendMode::kClear);
1139 this->drawClippedToSaveBehind(paint);
1140 }
1141
internalRestore()1142 void SkCanvas::internalRestore() {
1143 SkASSERT(!fMCStack.empty());
1144
1145 // now detach these from fMCRec so we can pop(). Gets freed after its drawn
1146 std::unique_ptr<Layer> layer = std::move(fMCRec->fLayer);
1147 std::unique_ptr<BackImage> backImage = std::move(fMCRec->fBackImage);
1148
1149 // now do the normal restore()
1150 fMCRec->~MCRec(); // balanced in save()
1151 fMCStack.pop_back();
1152 fMCRec = (MCRec*) fMCStack.back();
1153
1154 if (!fMCRec) {
1155 // This was the last record, restored during the destruction of the SkCanvas
1156 return;
1157 }
1158
1159 this->topDevice()->popClipStack();
1160 this->topDevice()->setGlobalCTM(fMCRec->fMatrix);
1161
1162 if (backImage) {
1163 SkPaint paint;
1164 paint.setBlendMode(SkBlendMode::kDstOver);
1165 this->topDevice()->drawSpecial(backImage->fImage.get(),
1166 SkMatrix::Translate(backImage->fLoc),
1167 SkSamplingOptions(),
1168 paint);
1169 }
1170
1171 // Draw the layer's device contents into the now-current older device. We can't call public
1172 // draw functions since we don't want to record them.
1173 if (layer && !layer->fDevice->isNoPixelsDevice() && !layer->fDiscard) {
1174 layer->fDevice->setImmutable();
1175
1176 // Don't go through AutoLayerForImageFilter since device draws are so closely tied to
1177 // internalSaveLayer and internalRestore.
1178 if (this->predrawNotify()) {
1179 SkDevice* dstDev = this->topDevice();
1180 if (!layer->fImageFilters.empty()) {
1181 auto compat = layer->fIncludesPadding ? DeviceCompatibleWithFilter::kYesWithPadding
1182 : DeviceCompatibleWithFilter::kYes;
1183 this->internalDrawDeviceWithFilter(layer->fDevice.get(), // src
1184 dstDev, // dst
1185 layer->fImageFilters,
1186 layer->fPaint,
1187 compat,
1188 layer->fDevice->imageInfo().colorInfo(),
1189 /*scaleFactor=*/1.0f,
1190 /*srcTileMode=*/SkTileMode::kDecal,
1191 layer->fIsCoverage);
1192 } else {
1193 // NOTE: We don't just call internalDrawDeviceWithFilter with a null filter
1194 // because we want to take advantage of overridden drawDevice functions for
1195 // document-based devices.
1196 SkASSERT(!layer->fIsCoverage && !layer->fIncludesPadding);
1197 SkSamplingOptions sampling;
1198 dstDev->drawDevice(layer->fDevice.get(), sampling, layer->fPaint);
1199 }
1200 }
1201 }
1202
1203 // Reset the clip restriction if the restore went past the save point that had added it.
1204 if (this->getSaveCount() < fClipRestrictionSaveCount) {
1205 fClipRestrictionRect.setEmpty();
1206 fClipRestrictionSaveCount = -1;
1207 }
1208 // Update the quick-reject bounds in case the restore changed the top device or the
1209 // removed save record had included modifications to the clip stack.
1210 fQuickRejectBounds = this->computeDeviceClipBounds();
1211 this->validateClip();
1212 }
1213
makeSurface(const SkImageInfo & info,const SkSurfaceProps * props)1214 sk_sp<SkSurface> SkCanvas::makeSurface(const SkImageInfo& info, const SkSurfaceProps* props) {
1215 if (nullptr == props) {
1216 props = &fProps;
1217 }
1218 return this->onNewSurface(info, *props);
1219 }
1220
onNewSurface(const SkImageInfo & info,const SkSurfaceProps & props)1221 sk_sp<SkSurface> SkCanvas::onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1222 return this->rootDevice()->makeSurface(info, props);
1223 }
1224
imageInfo() const1225 SkImageInfo SkCanvas::imageInfo() const {
1226 return this->onImageInfo();
1227 }
1228
onImageInfo() const1229 SkImageInfo SkCanvas::onImageInfo() const {
1230 return this->rootDevice()->imageInfo();
1231 }
1232
getProps(SkSurfaceProps * props) const1233 bool SkCanvas::getProps(SkSurfaceProps* props) const {
1234 return this->onGetProps(props, /*top=*/false);
1235 }
1236
getBaseProps() const1237 SkSurfaceProps SkCanvas::getBaseProps() const {
1238 SkSurfaceProps props;
1239 this->onGetProps(&props, /*top=*/false);
1240 return props;
1241 }
1242
getTopProps() const1243 SkSurfaceProps SkCanvas::getTopProps() const {
1244 SkSurfaceProps props;
1245 this->onGetProps(&props, /*top=*/true);
1246 return props;
1247 }
1248
onGetProps(SkSurfaceProps * props,bool top) const1249 bool SkCanvas::onGetProps(SkSurfaceProps* props, bool top) const {
1250 if (props) {
1251 *props = top ? topDevice()->surfaceProps() : fProps;
1252 }
1253 return true;
1254 }
1255
peekPixels(SkPixmap * pmap)1256 bool SkCanvas::peekPixels(SkPixmap* pmap) {
1257 return this->onPeekPixels(pmap);
1258 }
1259
onPeekPixels(SkPixmap * pmap)1260 bool SkCanvas::onPeekPixels(SkPixmap* pmap) {
1261 return this->rootDevice()->peekPixels(pmap);
1262 }
1263
accessTopLayerPixels(SkImageInfo * info,size_t * rowBytes,SkIPoint * origin)1264 void* SkCanvas::accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes, SkIPoint* origin) {
1265 SkPixmap pmap;
1266 if (!this->onAccessTopLayerPixels(&pmap)) {
1267 return nullptr;
1268 }
1269 if (info) {
1270 *info = pmap.info();
1271 }
1272 if (rowBytes) {
1273 *rowBytes = pmap.rowBytes();
1274 }
1275 if (origin) {
1276 // If the caller requested the origin, they presumably are expecting the returned pixels to
1277 // be axis-aligned with the root canvas. If the top level device isn't axis aligned, that's
1278 // not the case. Until we update accessTopLayerPixels() to accept a coord space matrix
1279 // instead of an origin, just don't expose the pixels in that case. Note that this means
1280 // that layers with complex coordinate spaces can still report their pixels if the caller
1281 // does not ask for the origin (e.g. just to dump its output to a file, etc).
1282 if (this->topDevice()->isPixelAlignedToGlobal()) {
1283 *origin = this->topDevice()->getOrigin();
1284 } else {
1285 return nullptr;
1286 }
1287 }
1288 return pmap.writable_addr();
1289 }
1290
onAccessTopLayerPixels(SkPixmap * pmap)1291 bool SkCanvas::onAccessTopLayerPixels(SkPixmap* pmap) {
1292 return this->topDevice()->accessPixels(pmap);
1293 }
1294
1295 /////////////////////////////////////////////////////////////////////////////
1296
translate(SkScalar dx,SkScalar dy)1297 void SkCanvas::translate(SkScalar dx, SkScalar dy) {
1298 if (dx || dy) {
1299 this->checkForDeferredSave();
1300 fMCRec->fMatrix.preTranslate(dx, dy);
1301
1302 this->topDevice()->setGlobalCTM(fMCRec->fMatrix);
1303
1304 this->didTranslate(dx,dy);
1305 }
1306 }
1307
scale(SkScalar sx,SkScalar sy)1308 void SkCanvas::scale(SkScalar sx, SkScalar sy) {
1309 if (sx != 1 || sy != 1) {
1310 this->checkForDeferredSave();
1311 fMCRec->fMatrix.preScale(sx, sy);
1312
1313 this->topDevice()->setGlobalCTM(fMCRec->fMatrix);
1314
1315 this->didScale(sx, sy);
1316 }
1317 }
1318
rotate(SkScalar degrees)1319 void SkCanvas::rotate(SkScalar degrees) {
1320 SkMatrix m;
1321 m.setRotate(degrees);
1322 this->concat(m);
1323 }
1324
rotate(SkScalar degrees,SkScalar px,SkScalar py)1325 void SkCanvas::rotate(SkScalar degrees, SkScalar px, SkScalar py) {
1326 SkMatrix m;
1327 m.setRotate(degrees, px, py);
1328 this->concat(m);
1329 }
1330
skew(SkScalar sx,SkScalar sy)1331 void SkCanvas::skew(SkScalar sx, SkScalar sy) {
1332 SkMatrix m;
1333 m.setSkew(sx, sy);
1334 this->concat(m);
1335 }
1336
concat(const SkMatrix & matrix)1337 void SkCanvas::concat(const SkMatrix& matrix) {
1338 if (matrix.isIdentity()) {
1339 return;
1340 }
1341 this->concat(SkM44(matrix));
1342 }
1343
internalConcat44(const SkM44 & m)1344 void SkCanvas::internalConcat44(const SkM44& m) {
1345 this->checkForDeferredSave();
1346
1347 fMCRec->fMatrix.preConcat(m);
1348
1349 this->topDevice()->setGlobalCTM(fMCRec->fMatrix);
1350 }
1351
concat(const SkM44 & m)1352 void SkCanvas::concat(const SkM44& m) {
1353 this->internalConcat44(m);
1354 // notify subclasses
1355 this->didConcat44(m);
1356 }
1357
internalSetMatrix(const SkM44 & m)1358 void SkCanvas::internalSetMatrix(const SkM44& m) {
1359 fMCRec->fMatrix = m;
1360
1361 this->topDevice()->setGlobalCTM(fMCRec->fMatrix);
1362 }
1363
setMatrix(const SkMatrix & matrix)1364 void SkCanvas::setMatrix(const SkMatrix& matrix) {
1365 this->setMatrix(SkM44(matrix));
1366 }
1367
setMatrix(const SkM44 & m)1368 void SkCanvas::setMatrix(const SkM44& m) {
1369 this->checkForDeferredSave();
1370 this->internalSetMatrix(m);
1371 this->didSetM44(m);
1372 }
1373
resetMatrix()1374 void SkCanvas::resetMatrix() {
1375 this->setMatrix(SkM44());
1376 }
1377
1378 //////////////////////////////////////////////////////////////////////////////
1379
clipRect(const SkRect & rect,SkClipOp op,bool doAA)1380 void SkCanvas::clipRect(const SkRect& rect, SkClipOp op, bool doAA) {
1381 if (!rect.isFinite()) {
1382 return;
1383 }
1384 this->checkForDeferredSave();
1385 ClipEdgeStyle edgeStyle = doAA ? kSoft_ClipEdgeStyle : kHard_ClipEdgeStyle;
1386 this->onClipRect(rect.makeSorted(), op, edgeStyle);
1387 }
1388
onClipRect(const SkRect & rect,SkClipOp op,ClipEdgeStyle edgeStyle)1389 void SkCanvas::onClipRect(const SkRect& rect, SkClipOp op, ClipEdgeStyle edgeStyle) {
1390 SkASSERT(rect.isSorted());
1391 const bool isAA = kSoft_ClipEdgeStyle == edgeStyle;
1392
1393 AutoUpdateQRBounds aqr(this);
1394 this->topDevice()->clipRect(rect, op, isAA);
1395 }
1396
androidFramework_setDeviceClipRestriction(const SkIRect & rect)1397 void SkCanvas::androidFramework_setDeviceClipRestriction(const SkIRect& rect) {
1398 // The device clip restriction is a surface-space rectangular intersection that cannot be
1399 // drawn outside of. The rectangle is remembered so that subsequent resetClip calls still
1400 // respect the restriction. Other than clip resetting, all clip operations restrict the set
1401 // of renderable pixels, so once set, the restriction will be respected until the canvas
1402 // save stack is restored past the point this function was invoked. Unfortunately, the current
1403 // implementation relies on the clip stack of the underyling SkDevices, which leads to some
1404 // awkward behavioral interactions (see skbug.com/12252).
1405 //
1406 // Namely, a canvas restore() could undo the clip restriction's rect, and if
1407 // setDeviceClipRestriction were called at a nested save level, there's no way to undo just the
1408 // prior restriction and re-apply the new one. It also only makes sense to apply to the base
1409 // device; any other device for a saved layer will be clipped back to the base device during its
1410 // matched restore. As such, we:
1411 // - Remember the save count that added the clip restriction and reset the rect to empty when
1412 // we've restored past that point to keep our state in sync with the device's clip stack.
1413 // - We assert that we're on the base device when this is invoked.
1414 // - We assert that setDeviceClipRestriction() is only called when there was no prior
1415 // restriction (cannot re-restrict, and prior state must have been reset by restoring the
1416 // canvas state).
1417 // - Historically, the empty rect would reset the clip restriction but it only could do so
1418 // partially since the device's clips wasn't adjusted. Resetting is now handled
1419 // automatically via SkCanvas::restore(), so empty input rects are skipped.
1420 SkASSERT(this->topDevice() == this->rootDevice()); // shouldn't be in a nested layer
1421 // and shouldn't already have a restriction
1422 SkASSERT(fClipRestrictionSaveCount < 0 && fClipRestrictionRect.isEmpty());
1423
1424 if (fClipRestrictionSaveCount < 0 && !rect.isEmpty()) {
1425 fClipRestrictionRect = rect;
1426 fClipRestrictionSaveCount = this->getSaveCount();
1427
1428 // A non-empty clip restriction immediately applies an intersection op (ignoring the ctm).
1429 // so we have to resolve the save.
1430 this->checkForDeferredSave();
1431 AutoUpdateQRBounds aqr(this);
1432 // Use clipRegion() since that operates in canvas-space, whereas clipRect() would apply the
1433 // device's current transform first.
1434 this->topDevice()->clipRegion(SkRegion(rect), SkClipOp::kIntersect);
1435 }
1436 }
1437
internal_private_resetClip()1438 void SkCanvas::internal_private_resetClip() {
1439 this->checkForDeferredSave();
1440 this->onResetClip();
1441 }
1442
onResetClip()1443 void SkCanvas::onResetClip() {
1444 SkIRect deviceRestriction = this->topDevice()->imageInfo().bounds();
1445 if (fClipRestrictionSaveCount >= 0 && this->topDevice() == this->rootDevice()) {
1446 // Respect the device clip restriction when resetting the clip if we're on the base device.
1447 // If we're not on the base device, then the "reset" applies to the top device's clip stack,
1448 // and the clip restriction will be respected automatically during a restore of the layer.
1449 if (!deviceRestriction.intersect(fClipRestrictionRect)) {
1450 deviceRestriction = SkIRect::MakeEmpty();
1451 }
1452 }
1453
1454 AutoUpdateQRBounds aqr(this);
1455 this->topDevice()->replaceClip(deviceRestriction);
1456 }
1457
clipRRect(const SkRRect & rrect,SkClipOp op,bool doAA)1458 void SkCanvas::clipRRect(const SkRRect& rrect, SkClipOp op, bool doAA) {
1459 this->checkForDeferredSave();
1460 ClipEdgeStyle edgeStyle = doAA ? kSoft_ClipEdgeStyle : kHard_ClipEdgeStyle;
1461 if (rrect.isRect()) {
1462 this->onClipRect(rrect.getBounds(), op, edgeStyle);
1463 } else {
1464 this->onClipRRect(rrect, op, edgeStyle);
1465 }
1466 }
1467
onClipRRect(const SkRRect & rrect,SkClipOp op,ClipEdgeStyle edgeStyle)1468 void SkCanvas::onClipRRect(const SkRRect& rrect, SkClipOp op, ClipEdgeStyle edgeStyle) {
1469 bool isAA = kSoft_ClipEdgeStyle == edgeStyle;
1470
1471 AutoUpdateQRBounds aqr(this);
1472 this->topDevice()->clipRRect(rrect, op, isAA);
1473 }
1474
clipPath(const SkPath & path,SkClipOp op,bool doAA)1475 void SkCanvas::clipPath(const SkPath& path, SkClipOp op, bool doAA) {
1476 this->checkForDeferredSave();
1477 ClipEdgeStyle edgeStyle = doAA ? kSoft_ClipEdgeStyle : kHard_ClipEdgeStyle;
1478
1479 if (!path.isInverseFillType() && fMCRec->fMatrix.asM33().rectStaysRect()) {
1480 SkRect r;
1481 if (path.isRect(&r)) {
1482 this->onClipRect(r, op, edgeStyle);
1483 return;
1484 }
1485 SkRRect rrect;
1486 if (path.isOval(&r)) {
1487 rrect.setOval(r);
1488 this->onClipRRect(rrect, op, edgeStyle);
1489 return;
1490 }
1491 if (path.isRRect(&rrect)) {
1492 this->onClipRRect(rrect, op, edgeStyle);
1493 return;
1494 }
1495 }
1496
1497 this->onClipPath(path, op, edgeStyle);
1498 }
1499
onClipPath(const SkPath & path,SkClipOp op,ClipEdgeStyle edgeStyle)1500 void SkCanvas::onClipPath(const SkPath& path, SkClipOp op, ClipEdgeStyle edgeStyle) {
1501 bool isAA = kSoft_ClipEdgeStyle == edgeStyle;
1502
1503 AutoUpdateQRBounds aqr(this);
1504 this->topDevice()->clipPath(path, op, isAA);
1505 }
1506
clipShader(sk_sp<SkShader> sh,SkClipOp op)1507 void SkCanvas::clipShader(sk_sp<SkShader> sh, SkClipOp op) {
1508 if (sh) {
1509 if (sh->isOpaque()) {
1510 if (op == SkClipOp::kIntersect) {
1511 // we don't occlude anything, so skip this call
1512 } else {
1513 SkASSERT(op == SkClipOp::kDifference);
1514 // we occlude everything, so set the clip to empty
1515 this->clipRect({0,0,0,0});
1516 }
1517 } else {
1518 this->checkForDeferredSave();
1519 this->onClipShader(std::move(sh), op);
1520 }
1521 }
1522 }
1523
onClipShader(sk_sp<SkShader> sh,SkClipOp op)1524 void SkCanvas::onClipShader(sk_sp<SkShader> sh, SkClipOp op) {
1525 AutoUpdateQRBounds aqr(this);
1526 this->topDevice()->clipShader(sh, op);
1527 }
1528
clipRegion(const SkRegion & rgn,SkClipOp op)1529 void SkCanvas::clipRegion(const SkRegion& rgn, SkClipOp op) {
1530 this->checkForDeferredSave();
1531 this->onClipRegion(rgn, op);
1532 }
1533
onClipRegion(const SkRegion & rgn,SkClipOp op)1534 void SkCanvas::onClipRegion(const SkRegion& rgn, SkClipOp op) {
1535 AutoUpdateQRBounds aqr(this);
1536 this->topDevice()->clipRegion(rgn, op);
1537 }
1538
validateClip() const1539 void SkCanvas::validateClip() const {
1540 #ifdef SK_DEBUG
1541 SkRect tmp = this->computeDeviceClipBounds();
1542 if (this->isClipEmpty()) {
1543 SkASSERT(fQuickRejectBounds.isEmpty());
1544 } else {
1545 SkASSERT(tmp == fQuickRejectBounds);
1546 }
1547 #endif
1548 }
1549
androidFramework_isClipAA() const1550 bool SkCanvas::androidFramework_isClipAA() const {
1551 return this->topDevice()->isClipAntiAliased();
1552 }
1553
temporary_internal_getRgnClip(SkRegion * rgn)1554 void SkCanvas::temporary_internal_getRgnClip(SkRegion* rgn) {
1555 rgn->setEmpty();
1556 SkDevice* device = this->topDevice();
1557 if (device && device->isPixelAlignedToGlobal()) {
1558 device->android_utils_clipAsRgn(rgn);
1559 SkIPoint origin = device->getOrigin();
1560 if (origin.x() | origin.y()) {
1561 rgn->translate(origin.x(), origin.y());
1562 }
1563 }
1564 }
1565
1566 ///////////////////////////////////////////////////////////////////////////////
1567
isClipEmpty() const1568 bool SkCanvas::isClipEmpty() const {
1569 return this->topDevice()->isClipEmpty();
1570 }
1571
isClipRect() const1572 bool SkCanvas::isClipRect() const {
1573 return this->topDevice()->isClipRect();
1574 }
1575
quickReject(const SkRect & src) const1576 bool SkCanvas::quickReject(const SkRect& src) const {
1577 #ifdef SK_DEBUG
1578 // Verify that fQuickRejectBounds are set properly.
1579 this->validateClip();
1580 #endif
1581
1582 SkRect devRect = SkMatrixPriv::MapRect(fMCRec->fMatrix, src);
1583 return !devRect.isFinite() || !devRect.intersects(fQuickRejectBounds);
1584 }
1585
quickReject(const SkPath & path) const1586 bool SkCanvas::quickReject(const SkPath& path) const {
1587 return path.isEmpty() || this->quickReject(path.getBounds());
1588 }
1589
internalQuickReject(const SkRect & bounds,const SkPaint & paint,const SkMatrix * matrix)1590 bool SkCanvas::internalQuickReject(const SkRect& bounds, const SkPaint& paint,
1591 const SkMatrix* matrix) {
1592 if (!bounds.isFinite() || paint.nothingToDraw()) {
1593 return true;
1594 }
1595
1596 if (paint.canComputeFastBounds()) {
1597 SkRect tmp = matrix ? matrix->mapRect(bounds) : bounds;
1598 return this->quickReject(paint.computeFastBounds(tmp, &tmp));
1599 }
1600
1601 return false;
1602 }
1603
1604
getLocalClipBounds() const1605 SkRect SkCanvas::getLocalClipBounds() const {
1606 SkIRect ibounds = this->getDeviceClipBounds();
1607 if (ibounds.isEmpty()) {
1608 return SkRect::MakeEmpty();
1609 }
1610
1611 SkMatrix inverse;
1612 // if we can't invert the CTM, we can't return local clip bounds
1613 if (!fMCRec->fMatrix.asM33().invert(&inverse)) {
1614 return SkRect::MakeEmpty();
1615 }
1616
1617 SkRect bounds;
1618 // adjust it outwards in case we are antialiasing
1619 const int margin = 1;
1620
1621 SkRect r = SkRect::Make(ibounds.makeOutset(margin, margin));
1622 inverse.mapRect(&bounds, r);
1623 return bounds;
1624 }
1625
getRoundInDeviceClipBounds() const1626 SkIRect SkCanvas::getRoundInDeviceClipBounds() const {
1627 return this->computeDeviceClipBounds(/*outsetForAA=*/false).roundIn();
1628 }
1629
getDeviceClipBounds() const1630 SkIRect SkCanvas::getDeviceClipBounds() const {
1631 return this->computeDeviceClipBounds(/*outsetForAA=*/false).roundOut();
1632 }
1633
computeDeviceClipBounds(bool outsetForAA) const1634 SkRect SkCanvas::computeDeviceClipBounds(bool outsetForAA) const {
1635 const SkDevice* dev = this->topDevice();
1636 if (dev->isClipEmpty()) {
1637 return SkRect::MakeEmpty();
1638 } else {
1639 SkRect devClipBounds =
1640 SkMatrixPriv::MapRect(dev->deviceToGlobal(), SkRect::Make(dev->devClipBounds()));
1641 if (outsetForAA) {
1642 // Expand bounds out by 1 in case we are anti-aliasing. We store the
1643 // bounds as floats to enable a faster quick reject implementation.
1644 devClipBounds.outset(1.f, 1.f);
1645 }
1646 return devClipBounds;
1647 }
1648 }
1649
1650 ///////////////////////////////////////////////////////////////////////
1651
getTotalMatrix() const1652 SkMatrix SkCanvas::getTotalMatrix() const {
1653 return fMCRec->fMatrix.asM33();
1654 }
1655
getLocalToDevice() const1656 SkM44 SkCanvas::getLocalToDevice() const {
1657 return fMCRec->fMatrix;
1658 }
1659
recordingContext() const1660 GrRecordingContext* SkCanvas::recordingContext() const {
1661 return this->topDevice()->recordingContext();
1662 }
1663
recorder() const1664 skgpu::graphite::Recorder* SkCanvas::recorder() const {
1665 return this->topDevice()->recorder();
1666 }
1667
drawDRRect(const SkRRect & outer,const SkRRect & inner,const SkPaint & paint)1668 void SkCanvas::drawDRRect(const SkRRect& outer, const SkRRect& inner,
1669 const SkPaint& paint) {
1670 TRACE_EVENT0("skia", TRACE_FUNC);
1671 if (outer.isEmpty()) {
1672 return;
1673 }
1674 if (inner.isEmpty()) {
1675 this->drawRRect(outer, paint);
1676 return;
1677 }
1678
1679 // We don't have this method (yet), but technically this is what we should
1680 // be able to return ...
1681 // if (!outer.contains(inner))) {
1682 //
1683 // For now at least check for containment of bounds
1684 if (!outer.getBounds().contains(inner.getBounds())) {
1685 return;
1686 }
1687
1688 this->onDrawDRRect(outer, inner, paint);
1689 }
1690
drawPaint(const SkPaint & paint)1691 void SkCanvas::drawPaint(const SkPaint& paint) {
1692 TRACE_EVENT0("skia", TRACE_FUNC);
1693 this->onDrawPaint(paint);
1694 }
1695
drawRect(const SkRect & r,const SkPaint & paint)1696 void SkCanvas::drawRect(const SkRect& r, const SkPaint& paint) {
1697 TRACE_EVENT0("skia", TRACE_FUNC);
1698 // To avoid redundant logic in our culling code and various backends, we always sort rects
1699 // before passing them along.
1700 this->onDrawRect(r.makeSorted(), paint);
1701 }
1702
drawClippedToSaveBehind(const SkPaint & paint)1703 void SkCanvas::drawClippedToSaveBehind(const SkPaint& paint) {
1704 TRACE_EVENT0("skia", TRACE_FUNC);
1705 this->onDrawBehind(paint);
1706 }
1707
drawRegion(const SkRegion & region,const SkPaint & paint)1708 void SkCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
1709 TRACE_EVENT0("skia", TRACE_FUNC);
1710 if (region.isEmpty()) {
1711 return;
1712 }
1713
1714 if (region.isRect()) {
1715 return this->drawIRect(region.getBounds(), paint);
1716 }
1717
1718 this->onDrawRegion(region, paint);
1719 }
1720
drawOval(const SkRect & r,const SkPaint & paint)1721 void SkCanvas::drawOval(const SkRect& r, const SkPaint& paint) {
1722 TRACE_EVENT0("skia", TRACE_FUNC);
1723 // To avoid redundant logic in our culling code and various backends, we always sort rects
1724 // before passing them along.
1725 this->onDrawOval(r.makeSorted(), paint);
1726 }
1727
drawRRect(const SkRRect & rrect,const SkPaint & paint)1728 void SkCanvas::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
1729 TRACE_EVENT0("skia", TRACE_FUNC);
1730 this->onDrawRRect(rrect, paint);
1731 }
1732
drawPoints(PointMode mode,size_t count,const SkPoint pts[],const SkPaint & paint)1733 void SkCanvas::drawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) {
1734 TRACE_EVENT0("skia", TRACE_FUNC);
1735 this->onDrawPoints(mode, count, pts, paint);
1736 }
1737
drawVertices(const sk_sp<SkVertices> & vertices,SkBlendMode mode,const SkPaint & paint)1738 void SkCanvas::drawVertices(const sk_sp<SkVertices>& vertices, SkBlendMode mode,
1739 const SkPaint& paint) {
1740 this->drawVertices(vertices.get(), mode, paint);
1741 }
1742
drawVertices(const SkVertices * vertices,SkBlendMode mode,const SkPaint & paint)1743 void SkCanvas::drawVertices(const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint) {
1744 TRACE_EVENT0("skia", TRACE_FUNC);
1745 RETURN_ON_NULL(vertices);
1746
1747 // We expect fans to be converted to triangles when building or deserializing SkVertices.
1748 SkASSERT(vertices->priv().mode() != SkVertices::kTriangleFan_VertexMode);
1749
1750 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1751 // Preserve legacy behavior for Android: ignore the SkShader if there are no texCoords present
1752 if (paint.getShader() && !vertices->priv().hasTexCoords()) {
1753 SkPaint noShaderPaint(paint);
1754 noShaderPaint.setShader(nullptr);
1755 this->onDrawVerticesObject(vertices, mode, noShaderPaint);
1756 return;
1757 }
1758 #endif
1759 this->onDrawVerticesObject(vertices, mode, paint);
1760 }
1761
drawMesh(const SkMesh & mesh,sk_sp<SkBlender> blender,const SkPaint & paint)1762 void SkCanvas::drawMesh(const SkMesh& mesh, sk_sp<SkBlender> blender, const SkPaint& paint) {
1763 TRACE_EVENT0("skia", TRACE_FUNC);
1764 if (!blender) {
1765 blender = SkBlender::Mode(SkBlendMode::kModulate);
1766 }
1767 this->onDrawMesh(mesh, std::move(blender), paint);
1768 }
1769
drawPath(const SkPath & path,const SkPaint & paint)1770 void SkCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
1771 TRACE_EVENT0("skia", TRACE_FUNC);
1772 this->onDrawPath(path, paint);
1773 }
1774
1775 // Returns true if the rect can be "filled" : non-empty and finite
fillable(const SkRect & r)1776 static bool fillable(const SkRect& r) {
1777 SkScalar w = r.width();
1778 SkScalar h = r.height();
1779 return SkIsFinite(w, h) && w > 0 && h > 0;
1780 }
1781
clean_paint_for_lattice(const SkPaint * paint)1782 static SkPaint clean_paint_for_lattice(const SkPaint* paint) {
1783 SkPaint cleaned;
1784 if (paint) {
1785 cleaned = *paint;
1786 cleaned.setMaskFilter(nullptr);
1787 cleaned.setAntiAlias(false);
1788 }
1789 return cleaned;
1790 }
1791
drawImageNine(const SkImage * image,const SkIRect & center,const SkRect & dst,SkFilterMode filter,const SkPaint * paint)1792 void SkCanvas::drawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
1793 SkFilterMode filter, const SkPaint* paint) {
1794 RETURN_ON_NULL(image);
1795
1796 const int xdivs[] = {center.fLeft, center.fRight};
1797 const int ydivs[] = {center.fTop, center.fBottom};
1798
1799 Lattice lat;
1800 lat.fXDivs = xdivs;
1801 lat.fYDivs = ydivs;
1802 lat.fRectTypes = nullptr;
1803 lat.fXCount = lat.fYCount = 2;
1804 lat.fBounds = nullptr;
1805 lat.fColors = nullptr;
1806 this->drawImageLattice(image, lat, dst, filter, paint);
1807 }
1808
drawImageLattice(const SkImage * image,const Lattice & lattice,const SkRect & dst,SkFilterMode filter,const SkPaint * paint)1809 void SkCanvas::drawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
1810 SkFilterMode filter, const SkPaint* paint) {
1811 TRACE_EVENT0("skia", TRACE_FUNC);
1812 RETURN_ON_NULL(image);
1813 if (dst.isEmpty()) {
1814 return;
1815 }
1816
1817 SkIRect bounds;
1818 Lattice latticePlusBounds = lattice;
1819 if (!latticePlusBounds.fBounds) {
1820 bounds = SkIRect::MakeWH(image->width(), image->height());
1821 latticePlusBounds.fBounds = &bounds;
1822 }
1823
1824 SkPaint latticePaint = clean_paint_for_lattice(paint);
1825 if (SkLatticeIter::Valid(image->width(), image->height(), latticePlusBounds)) {
1826 this->onDrawImageLattice2(image, latticePlusBounds, dst, filter, &latticePaint);
1827 } else {
1828 this->drawImageRect(image, SkRect::MakeIWH(image->width(), image->height()), dst,
1829 SkSamplingOptions(filter), &latticePaint, kStrict_SrcRectConstraint);
1830 }
1831 }
1832
drawAtlas(const SkImage * atlas,const SkRSXform xform[],const SkRect tex[],const SkColor colors[],int count,SkBlendMode mode,const SkSamplingOptions & sampling,const SkRect * cull,const SkPaint * paint)1833 void SkCanvas::drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
1834 const SkColor colors[], int count, SkBlendMode mode,
1835 const SkSamplingOptions& sampling, const SkRect* cull,
1836 const SkPaint* paint) {
1837 TRACE_EVENT0("skia", TRACE_FUNC);
1838 RETURN_ON_NULL(atlas);
1839 if (count <= 0) {
1840 return;
1841 }
1842 SkASSERT(atlas);
1843 SkASSERT(tex);
1844 this->onDrawAtlas2(atlas, xform, tex, colors, count, mode, sampling, cull, paint);
1845 }
1846
drawAnnotation(const SkRect & rect,const char key[],SkData * value)1847 void SkCanvas::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
1848 TRACE_EVENT0("skia", TRACE_FUNC);
1849 if (key) {
1850 this->onDrawAnnotation(rect, key, value);
1851 }
1852 }
1853
private_draw_shadow_rec(const SkPath & path,const SkDrawShadowRec & rec)1854 void SkCanvas::private_draw_shadow_rec(const SkPath& path, const SkDrawShadowRec& rec) {
1855 TRACE_EVENT0("skia", TRACE_FUNC);
1856 this->onDrawShadowRec(path, rec);
1857 }
1858
onDrawShadowRec(const SkPath & path,const SkDrawShadowRec & rec)1859 void SkCanvas::onDrawShadowRec(const SkPath& path, const SkDrawShadowRec& rec) {
1860 // We don't test quickReject because the shadow outsets the path's bounds.
1861 // TODO(michaelludwig): Is it worth calling SkDrawShadowMetrics::GetLocalBounds here?
1862 if (!this->predrawNotify()) {
1863 return;
1864 }
1865 this->topDevice()->drawShadow(path, rec);
1866 }
1867
experimental_DrawEdgeAAQuad(const SkRect & rect,const SkPoint clip[4],QuadAAFlags aaFlags,const SkColor4f & color,SkBlendMode mode)1868 void SkCanvas::experimental_DrawEdgeAAQuad(const SkRect& rect, const SkPoint clip[4],
1869 QuadAAFlags aaFlags, const SkColor4f& color,
1870 SkBlendMode mode) {
1871 TRACE_EVENT0("skia", TRACE_FUNC);
1872 // Make sure the rect is sorted before passing it along
1873 this->onDrawEdgeAAQuad(rect.makeSorted(), clip, aaFlags, color, mode);
1874 }
1875
experimental_DrawEdgeAAImageSet(const ImageSetEntry imageSet[],int cnt,const SkPoint dstClips[],const SkMatrix preViewMatrices[],const SkSamplingOptions & sampling,const SkPaint * paint,SrcRectConstraint constraint)1876 void SkCanvas::experimental_DrawEdgeAAImageSet(const ImageSetEntry imageSet[], int cnt,
1877 const SkPoint dstClips[],
1878 const SkMatrix preViewMatrices[],
1879 const SkSamplingOptions& sampling,
1880 const SkPaint* paint,
1881 SrcRectConstraint constraint) {
1882 TRACE_EVENT0("skia", TRACE_FUNC);
1883 // Route single, rectangular quads to drawImageRect() to take advantage of image filter
1884 // optimizations that avoid a layer.
1885 if (paint && paint->getImageFilter() && cnt == 1) {
1886 const auto& entry = imageSet[0];
1887 // If the preViewMatrix is skipped or a positive-scale + translate matrix, we can apply it
1888 // to the entry's dstRect w/o changing output behavior.
1889 const bool canMapDstRect = entry.fMatrixIndex < 0 ||
1890 (preViewMatrices[entry.fMatrixIndex].isScaleTranslate() &&
1891 preViewMatrices[entry.fMatrixIndex].getScaleX() > 0.f &&
1892 preViewMatrices[entry.fMatrixIndex].getScaleY() > 0.f);
1893 if (!entry.fHasClip && canMapDstRect) {
1894 SkRect dst = entry.fDstRect;
1895 if (entry.fMatrixIndex >= 0) {
1896 preViewMatrices[entry.fMatrixIndex].mapRect(&dst);
1897 }
1898 this->drawImageRect(entry.fImage.get(), entry.fSrcRect, dst,
1899 sampling, paint, constraint);
1900 return;
1901 } // Else the entry is doing more than can be represented by drawImageRect
1902 } // Else no filter, or many entries that should be filtered together
1903 this->onDrawEdgeAAImageSet2(imageSet, cnt, dstClips, preViewMatrices, sampling, paint,
1904 constraint);
1905 }
1906
1907 //////////////////////////////////////////////////////////////////////////////
1908 // These are the virtual drawing methods
1909 //////////////////////////////////////////////////////////////////////////////
1910
onDiscard()1911 void SkCanvas::onDiscard() {
1912 if (fSurfaceBase) {
1913 sk_ignore_unused_variable(fSurfaceBase->aboutToDraw(SkSurface::kDiscard_ContentChangeMode));
1914 }
1915 }
1916
onDrawPaint(const SkPaint & paint)1917 void SkCanvas::onDrawPaint(const SkPaint& paint) {
1918 this->internalDrawPaint(paint);
1919 }
1920
internalDrawPaint(const SkPaint & paint)1921 void SkCanvas::internalDrawPaint(const SkPaint& paint) {
1922 // drawPaint does not call internalQuickReject() because computing its geometry is not free
1923 // (see getLocalClipBounds(), and the two conditions below are sufficient.
1924 if (paint.nothingToDraw() || this->isClipEmpty()) {
1925 return;
1926 }
1927
1928 auto layer = this->aboutToDraw(paint, nullptr, PredrawFlags::kCheckForOverwrite);
1929 if (layer) {
1930 this->topDevice()->drawPaint(layer->paint());
1931 }
1932 }
1933
onDrawPoints(PointMode mode,size_t count,const SkPoint pts[],const SkPaint & paint)1934 void SkCanvas::onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
1935 const SkPaint& paint) {
1936 if ((long)count <= 0 || paint.nothingToDraw()) {
1937 return;
1938 }
1939 SkASSERT(pts != nullptr);
1940
1941 SkRect bounds;
1942 // Compute bounds from points (common for drawing a single line)
1943 if (count == 2) {
1944 bounds.set(pts[0], pts[1]);
1945 } else {
1946 bounds.setBounds(pts, SkToInt(count));
1947 }
1948
1949 // Enforce paint style matches implicit behavior of drawPoints
1950 SkPaint strokePaint = paint;
1951 strokePaint.setStyle(SkPaint::kStroke_Style);
1952 if (this->internalQuickReject(bounds, strokePaint)) {
1953 return;
1954 }
1955
1956 auto layer = this->aboutToDraw(strokePaint, &bounds);
1957 if (layer) {
1958 this->topDevice()->drawPoints(mode, count, pts, layer->paint());
1959 }
1960 }
1961
can_attempt_blurred_rrect_draw(const SkPaint & paint)1962 static const SkBlurMaskFilterImpl* can_attempt_blurred_rrect_draw(const SkPaint& paint) {
1963 if (paint.getPathEffect()) {
1964 return nullptr;
1965 }
1966
1967 // TODO: Once stroke-and-fill goes away, we can check the paint's style directly.
1968 if (SkStrokeRec(paint).getStyle() != SkStrokeRec::kFill_Style) {
1969 return nullptr;
1970 }
1971
1972 const SkMaskFilterBase* maskFilter = as_MFB(paint.getMaskFilter());
1973 if (!maskFilter || maskFilter->type() != SkMaskFilterBase::Type::kBlur) {
1974 return nullptr;
1975 }
1976
1977 const SkBlurMaskFilterImpl* blurMaskFilter =
1978 static_cast<const SkBlurMaskFilterImpl*>(maskFilter);
1979 if (blurMaskFilter->blurStyle() != kNormal_SkBlurStyle) {
1980 return nullptr;
1981 }
1982
1983 return blurMaskFilter;
1984 }
1985
attemptBlurredRRectDraw(const SkRRect & rrect,const SkPaint & paint,SkEnumBitMask<PredrawFlags> flags)1986 std::optional<AutoLayerForImageFilter> SkCanvas::attemptBlurredRRectDraw(
1987 const SkRRect& rrect, const SkPaint& paint, SkEnumBitMask<PredrawFlags> flags) {
1988 SkASSERT(!(flags & PredrawFlags::kSkipMaskFilterAutoLayer));
1989 const SkRect& bounds = rrect.getBounds();
1990
1991 if (!this->topDevice()->useDrawCoverageMaskForMaskFilters()) {
1992 // Regular draw in the legacy mask filter case.
1993 return this->aboutToDraw(paint, &bounds, flags);
1994 }
1995
1996 if (!this->getTotalMatrix().isSimilarity()) {
1997 // TODO: If the CTM does more than just translation, rotation, and uniform scale, then the
1998 // results of analytic blurring will be different than mask filter blurring. Skip the
1999 // specialized path in this case.
2000 return this->aboutToDraw(paint, &bounds, flags);
2001 }
2002
2003 const SkBlurMaskFilterImpl* blurMaskFilter = can_attempt_blurred_rrect_draw(paint);
2004 if (!blurMaskFilter) {
2005 // Can't attempt a specialized blurred draw, so do a regular draw.
2006 return this->aboutToDraw(paint, &bounds, flags);
2007 }
2008
2009 auto layer = this->aboutToDraw(paint, &bounds, flags | PredrawFlags::kSkipMaskFilterAutoLayer);
2010 if (!layer) {
2011 // predrawNotify failed.
2012 return std::nullopt;
2013 }
2014
2015 const float deviceSigma = blurMaskFilter->computeXformedSigma(this->getTotalMatrix());
2016 if (this->topDevice()->drawBlurredRRect(rrect, layer->paint(), deviceSigma)) {
2017 // Analytic draw was successful.
2018 return std::nullopt;
2019 }
2020
2021 // Fall back on a regular draw, adding any mask filter layer we skipped earlier. We know the
2022 // paint has a mask filter here, otherwise we would have failed the can_attempt check above.
2023 layer->addMaskFilterLayer(&bounds);
2024 return layer;
2025 }
2026
onDrawRect(const SkRect & r,const SkPaint & paint)2027 void SkCanvas::onDrawRect(const SkRect& r, const SkPaint& paint) {
2028 SkASSERT(r.isSorted());
2029 if (this->internalQuickReject(r, paint)) {
2030 return;
2031 }
2032
2033 // Returns a layer if a blurred draw is not applicable or was unsuccessful.
2034 std::optional<AutoLayerForImageFilter> layer = this->attemptBlurredRRectDraw(
2035 SkRRect::MakeRect(r), paint, PredrawFlags::kCheckForOverwrite);
2036
2037 if (layer) {
2038 this->topDevice()->drawRect(r, layer->paint());
2039 }
2040 }
2041
onDrawRegion(const SkRegion & region,const SkPaint & paint)2042 void SkCanvas::onDrawRegion(const SkRegion& region, const SkPaint& paint) {
2043 const SkRect bounds = SkRect::Make(region.getBounds());
2044 if (this->internalQuickReject(bounds, paint)) {
2045 return;
2046 }
2047
2048 auto layer = this->aboutToDraw(paint, &bounds);
2049 if (layer) {
2050 this->topDevice()->drawRegion(region, layer->paint());
2051 }
2052 }
2053
onDrawBehind(const SkPaint & paint)2054 void SkCanvas::onDrawBehind(const SkPaint& paint) {
2055 SkDevice* dev = this->topDevice();
2056 if (!dev) {
2057 return;
2058 }
2059
2060 SkIRect bounds;
2061 SkDeque::Iter iter(fMCStack, SkDeque::Iter::kBack_IterStart);
2062 for (;;) {
2063 const MCRec* rec = (const MCRec*)iter.prev();
2064 if (!rec) {
2065 return; // no backimages, so nothing to draw
2066 }
2067 if (rec->fBackImage) {
2068 // drawBehind should only have been called when the saveBehind record is active;
2069 // if this fails, it means a real saveLayer was made w/o being restored first.
2070 SkASSERT(dev == rec->fDevice);
2071 bounds = SkIRect::MakeXYWH(rec->fBackImage->fLoc.fX, rec->fBackImage->fLoc.fY,
2072 rec->fBackImage->fImage->width(),
2073 rec->fBackImage->fImage->height());
2074 break;
2075 }
2076 }
2077
2078 // The backimage location (and thus bounds) were defined in the device's space, so mark it
2079 // as a clip. We use a clip instead of just drawing a rect in case the paint has an image
2080 // filter on it (which is applied before any auto-layer so the filter is clipped).
2081 dev->pushClipStack();
2082 {
2083 // We also have to temporarily whack the device matrix since clipRegion is affected by the
2084 // global-to-device matrix and clipRect is affected by the local-to-device.
2085 SkAutoDeviceTransformRestore adtr(dev, SkMatrix::I());
2086 dev->clipRect(SkRect::Make(bounds), SkClipOp::kIntersect, /* aa */ false);
2087 // ~adtr will reset the local-to-device matrix so that drawPaint() shades correctly.
2088 }
2089
2090 auto layer = this->aboutToDraw(paint);
2091 if (layer) {
2092 this->topDevice()->drawPaint(layer->paint());
2093 }
2094
2095 dev->popClipStack();
2096 }
2097
onDrawOval(const SkRect & oval,const SkPaint & paint)2098 void SkCanvas::onDrawOval(const SkRect& oval, const SkPaint& paint) {
2099 SkASSERT(oval.isSorted());
2100 if (this->internalQuickReject(oval, paint)) {
2101 return;
2102 }
2103
2104 // Returns a layer if a blurred draw is not applicable or was unsuccessful.
2105 std::optional<AutoLayerForImageFilter> layer =
2106 this->attemptBlurredRRectDraw(SkRRect::MakeOval(oval), paint, PredrawFlags::kNone);
2107
2108 if (layer) {
2109 this->topDevice()->drawOval(oval, layer->paint());
2110 }
2111 }
2112
onDrawArc(const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const SkPaint & paint)2113 void SkCanvas::onDrawArc(const SkRect& oval, SkScalar startAngle,
2114 SkScalar sweepAngle, bool useCenter,
2115 const SkPaint& paint) {
2116 SkASSERT(oval.isSorted());
2117 if (this->internalQuickReject(oval, paint)) {
2118 return;
2119 }
2120
2121 auto layer = this->aboutToDraw(paint, &oval);
2122 if (layer) {
2123 this->topDevice()->drawArc(SkArc::Make(oval, startAngle, sweepAngle, useCenter),
2124 layer->paint());
2125 }
2126 }
2127
onDrawRRect(const SkRRect & rrect,const SkPaint & paint)2128 void SkCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) {
2129 const SkRect& bounds = rrect.getBounds();
2130
2131 // Delegating to simpler draw operations
2132 if (rrect.isRect()) {
2133 // call the non-virtual version
2134 this->SkCanvas::drawRect(bounds, paint);
2135 return;
2136 } else if (rrect.isOval()) {
2137 // call the non-virtual version
2138 this->SkCanvas::drawOval(bounds, paint);
2139 return;
2140 }
2141
2142 if (this->internalQuickReject(bounds, paint)) {
2143 return;
2144 }
2145
2146 // Returns a layer if a blurred draw is not applicable or was unsuccessful.
2147 std::optional<AutoLayerForImageFilter> layer =
2148 this->attemptBlurredRRectDraw(rrect, paint, PredrawFlags::kNone);
2149
2150 if (layer) {
2151 this->topDevice()->drawRRect(rrect, layer->paint());
2152 }
2153 }
2154
onDrawDRRect(const SkRRect & outer,const SkRRect & inner,const SkPaint & paint)2155 void SkCanvas::onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
2156 const SkRect& bounds = outer.getBounds();
2157 if (this->internalQuickReject(bounds, paint)) {
2158 return;
2159 }
2160
2161 auto layer = this->aboutToDraw(paint, &bounds);
2162 if (layer) {
2163 this->topDevice()->drawDRRect(outer, inner, layer->paint());
2164 }
2165 }
2166
onDrawPath(const SkPath & path,const SkPaint & paint)2167 void SkCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {
2168 if (!path.isFinite()) {
2169 return;
2170 }
2171
2172 const SkRect& pathBounds = path.getBounds();
2173 if (!path.isInverseFillType() && this->internalQuickReject(pathBounds, paint)) {
2174 return;
2175 }
2176 if (path.isInverseFillType() && pathBounds.width() <= 0 && pathBounds.height() <= 0) {
2177 this->internalDrawPaint(paint);
2178 return;
2179 }
2180
2181 auto layer = this->aboutToDraw(paint, path.isInverseFillType() ? nullptr : &pathBounds);
2182 if (layer) {
2183 this->topDevice()->drawPath(path, layer->paint());
2184 }
2185 }
2186
2187 // Clean-up the paint to match the drawing semantics for drawImage et al. (skbug.com/7804).
clean_paint_for_drawImage(const SkPaint * paint)2188 static SkPaint clean_paint_for_drawImage(const SkPaint* paint) {
2189 SkPaint cleaned;
2190 if (paint) {
2191 cleaned = *paint;
2192 cleaned.setStyle(SkPaint::kFill_Style);
2193 cleaned.setPathEffect(nullptr);
2194 }
2195 return cleaned;
2196 }
2197
2198 // drawVertices fills triangles and ignores mask filter and path effect,
2199 // so canonicalize the paint before checking quick reject.
clean_paint_for_drawVertices(SkPaint paint)2200 static SkPaint clean_paint_for_drawVertices(SkPaint paint) {
2201 paint.setStyle(SkPaint::kFill_Style);
2202 paint.setMaskFilter(nullptr);
2203 paint.setPathEffect(nullptr);
2204 return paint;
2205 }
2206
2207 // TODO: Delete this since it is no longer used
onDrawImage2(const SkImage * image,SkScalar x,SkScalar y,const SkSamplingOptions & sampling,const SkPaint * paint)2208 void SkCanvas::onDrawImage2(const SkImage* image, SkScalar x, SkScalar y,
2209 const SkSamplingOptions& sampling, const SkPaint* paint) {
2210 SkUNREACHABLE;
2211 }
2212
clean_sampling_for_constraint(const SkSamplingOptions & sampling,SkCanvas::SrcRectConstraint constraint)2213 static SkSamplingOptions clean_sampling_for_constraint(
2214 const SkSamplingOptions& sampling,
2215 SkCanvas::SrcRectConstraint constraint) {
2216 if (constraint == SkCanvas::kStrict_SrcRectConstraint) {
2217 if (sampling.mipmap != SkMipmapMode::kNone) {
2218 return SkSamplingOptions(sampling.filter);
2219 }
2220 if (sampling.isAniso()) {
2221 return SkSamplingOptions(SkFilterMode::kLinear);
2222 }
2223 }
2224 return sampling;
2225 }
2226
onDrawImageRect2(const SkImage * image,const SkRect & src,const SkRect & dst,const SkSamplingOptions & sampling,const SkPaint * paint,SrcRectConstraint constraint)2227 void SkCanvas::onDrawImageRect2(const SkImage* image, const SkRect& src, const SkRect& dst,
2228 const SkSamplingOptions& sampling, const SkPaint* paint,
2229 SrcRectConstraint constraint) {
2230 SkPaint realPaint = clean_paint_for_drawImage(paint);
2231 SkSamplingOptions realSampling = clean_sampling_for_constraint(sampling, constraint);
2232
2233 if (this->internalQuickReject(dst, realPaint)) {
2234 return;
2235 }
2236
2237 if (this->topDevice()->shouldDrawAsTiledImageRect()) {
2238 if (this->topDevice()->drawAsTiledImageRect(
2239 this, image, &src, dst, realSampling, realPaint, constraint)) {
2240 return;
2241 }
2242 }
2243
2244 // drawImageRect()'s behavior is modified by the presence of an image filter, a mask filter, a
2245 // color filter, the paint's alpha, the paint's blender, and--when it's an alpha-only image--
2246 // the paint's color or shader. When there's an image filter, the paint's blender is applied to
2247 // the result of the image filter function, but every other aspect would influence the source
2248 // image that's then rendered with src-over blending into a transparent temporary layer.
2249 //
2250 // However, skif::FilterResult can apply the paint alpha and any color filter often without
2251 // requiring a layer, and src-over blending onto a transparent dst is a no-op, so we can use the
2252 // input image directly as the source for filtering. When the image is alpha-only and must be
2253 // colorized, or when a mask filter would change the coverage we skip this optimization for
2254 // simplicity since *somehow* embedding colorization or mask blurring into the filter graph
2255 // would likely be equivalent to using the existing AutoLayerForImageFilter functionality.
2256 if (realPaint.getImageFilter() && !image->isAlphaOnly() && !realPaint.getMaskFilter()) {
2257 SkDevice* device = this->topDevice();
2258
2259 skif::ParameterSpace<SkRect> imageBounds{dst};
2260 skif::DeviceSpace<SkIRect> outputBounds{device->devClipBounds()};
2261 FilterToSpan filterAsSpan(realPaint.getImageFilter());
2262 auto mappingAndBounds = get_layer_mapping_and_bounds(filterAsSpan,
2263 device->localToDevice(),
2264 outputBounds,
2265 imageBounds);
2266 if (!mappingAndBounds) {
2267 return;
2268 }
2269 if (!this->predrawNotify()) {
2270 return;
2271 }
2272
2273 // Start out with an empty source image, to be replaced with the converted 'image', and a
2274 // desired output equal to the calculated initial source layer bounds, which accounts for
2275 // how the image filters will access 'image' (possibly different than just 'outputBounds').
2276 auto backend = device->createImageFilteringBackend(
2277 device->surfaceProps(),
2278 image_filter_color_type(device->imageInfo().colorInfo()));
2279 auto [mapping, srcBounds] = *mappingAndBounds;
2280 skif::Stats stats;
2281 skif::Context ctx{std::move(backend),
2282 mapping,
2283 srcBounds,
2284 skif::FilterResult{},
2285 device->imageInfo().colorSpace(),
2286 &stats};
2287
2288 auto source = skif::FilterResult::MakeFromImage(
2289 ctx, sk_ref_sp(image), src, imageBounds, sampling);
2290 // Apply effects that are normally processed on the draw *before* any layer/image filter.
2291 source = apply_alpha_and_colorfilter(ctx, source, realPaint);
2292
2293 // Evaluate the image filter, with a context pointing to the source created directly from
2294 // 'image' (which will not require intermediate renderpasses when 'src' is integer aligned).
2295 // and a desired output matching the device clip bounds.
2296 ctx = ctx.withNewDesiredOutput(mapping.deviceToLayer(outputBounds))
2297 .withNewSource(source);
2298 auto result = as_IFB(realPaint.getImageFilter())->filterImage(ctx);
2299 result.draw(ctx, device, realPaint.getBlender());
2300 stats.reportStats();
2301 return;
2302 }
2303
2304 // When there's a alpha-only image that must be colorized or a mask filter to apply, go through
2305 // the regular auto-layer-for-imagefilter process
2306 if (realPaint.getMaskFilter() && this->topDevice()->useDrawCoverageMaskForMaskFilters()) {
2307 // Route mask-filtered drawImages to drawRect() to use the auto-layer for mask filters,
2308 // which require all shading to be encoded in the paint.
2309 SkRect drawDst = SkModifyPaintAndDstForDrawImageRect(
2310 image, sampling, src, dst, constraint == kStrict_SrcRectConstraint, &realPaint);
2311 if (drawDst.isEmpty()) {
2312 return;
2313 } else {
2314 this->drawRect(drawDst, realPaint);
2315 return;
2316 }
2317 }
2318
2319 auto layer = this->aboutToDraw(realPaint, &dst,
2320 PredrawFlags::kCheckForOverwrite |
2321 (image->isOpaque() ? PredrawFlags::kOpaqueShaderOverride
2322 : PredrawFlags::kNonOpaqueShaderOverride));
2323 if (layer) {
2324 this->topDevice()->drawImageRect(image, &src, dst, realSampling, layer->paint(),
2325 constraint);
2326 }
2327 }
2328
onDrawImageLattice2(const SkImage * image,const Lattice & lattice,const SkRect & dst,SkFilterMode filter,const SkPaint * paint)2329 void SkCanvas::onDrawImageLattice2(const SkImage* image, const Lattice& lattice, const SkRect& dst,
2330 SkFilterMode filter, const SkPaint* paint) {
2331 SkPaint realPaint = clean_paint_for_drawImage(paint);
2332
2333 if (this->internalQuickReject(dst, realPaint)) {
2334 return;
2335 }
2336
2337 auto layer = this->aboutToDraw(realPaint, &dst);
2338 if (layer) {
2339 this->topDevice()->drawImageLattice(image, lattice, dst, filter, layer->paint());
2340 }
2341 }
2342
drawImage(const SkImage * image,SkScalar x,SkScalar y,const SkSamplingOptions & sampling,const SkPaint * paint)2343 void SkCanvas::drawImage(const SkImage* image, SkScalar x, SkScalar y,
2344 const SkSamplingOptions& sampling, const SkPaint* paint) {
2345 TRACE_EVENT0("skia", TRACE_FUNC);
2346 RETURN_ON_NULL(image);
2347
2348 this->drawImageRect(image,
2349 /*src=*/SkRect::MakeWH(image->width(), image->height()),
2350 /*dst=*/SkRect::MakeXYWH(x, y, image->width(), image->height()),
2351 sampling,
2352 paint,
2353 kFast_SrcRectConstraint);
2354 }
2355
drawImageRect(const SkImage * image,const SkRect & src,const SkRect & dst,const SkSamplingOptions & sampling,const SkPaint * paint,SrcRectConstraint constraint)2356 void SkCanvas::drawImageRect(const SkImage* image, const SkRect& src, const SkRect& dst,
2357 const SkSamplingOptions& sampling, const SkPaint* paint,
2358 SrcRectConstraint constraint) {
2359 RETURN_ON_NULL(image);
2360 if (!fillable(dst) || !fillable(src)) {
2361 return;
2362 }
2363 this->onDrawImageRect2(image, src, dst, sampling, paint, constraint);
2364 }
2365
drawImageRect(const SkImage * image,const SkRect & dst,const SkSamplingOptions & sampling,const SkPaint * paint)2366 void SkCanvas::drawImageRect(const SkImage* image, const SkRect& dst,
2367 const SkSamplingOptions& sampling, const SkPaint* paint) {
2368 RETURN_ON_NULL(image);
2369 this->drawImageRect(image, SkRect::MakeIWH(image->width(), image->height()), dst, sampling,
2370 paint, kFast_SrcRectConstraint);
2371 }
2372
onDrawTextBlob(const SkTextBlob * blob,SkScalar x,SkScalar y,const SkPaint & paint)2373 void SkCanvas::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
2374 const SkPaint& paint) {
2375 auto glyphRunList = fScratchGlyphRunBuilder->blobToGlyphRunList(*blob, {x, y});
2376 this->onDrawGlyphRunList(glyphRunList, paint);
2377 }
2378
onDrawGlyphRunList(const sktext::GlyphRunList & glyphRunList,const SkPaint & paint)2379 void SkCanvas::onDrawGlyphRunList(const sktext::GlyphRunList& glyphRunList, const SkPaint& paint) {
2380 SkRect bounds = glyphRunList.sourceBoundsWithOrigin();
2381 if (this->internalQuickReject(bounds, paint)) {
2382 return;
2383 }
2384
2385 // Text attempts to apply any SkMaskFilter internally and save the blurred masks in the
2386 // strike cache; if a glyph must be drawn as a path or drawable, SkDevice routes back to
2387 // this SkCanvas to retry, which will go through a function that does *not* skip the mask
2388 // filter layer.
2389 auto layer = this->aboutToDraw(paint, &bounds, PredrawFlags::kSkipMaskFilterAutoLayer);
2390 if (layer) {
2391 this->topDevice()->drawGlyphRunList(this, glyphRunList, layer->paint());
2392 }
2393 }
2394
convertBlobToSlug(const SkTextBlob & blob,SkPoint origin,const SkPaint & paint)2395 sk_sp<Slug> SkCanvas::convertBlobToSlug(
2396 const SkTextBlob& blob, SkPoint origin, const SkPaint& paint) {
2397 TRACE_EVENT0("skia", TRACE_FUNC);
2398 auto glyphRunList = fScratchGlyphRunBuilder->blobToGlyphRunList(blob, origin);
2399 return this->onConvertGlyphRunListToSlug(glyphRunList, paint);
2400 }
2401
onConvertGlyphRunListToSlug(const sktext::GlyphRunList & glyphRunList,const SkPaint & paint)2402 sk_sp<Slug> SkCanvas::onConvertGlyphRunListToSlug(const sktext::GlyphRunList& glyphRunList,
2403 const SkPaint& paint) {
2404 SkRect bounds = glyphRunList.sourceBoundsWithOrigin();
2405 if (bounds.isEmpty() || !bounds.isFinite() || paint.nothingToDraw()) {
2406 return nullptr;
2407 }
2408 // See comment in onDrawGlyphRunList()
2409 auto layer = this->aboutToDraw(paint, &bounds, PredrawFlags::kSkipMaskFilterAutoLayer);
2410 if (layer) {
2411 return this->topDevice()->convertGlyphRunListToSlug(glyphRunList, layer->paint());
2412 }
2413 return nullptr;
2414 }
2415
drawSlug(const Slug * slug,const SkPaint & paint)2416 void SkCanvas::drawSlug(const Slug* slug, const SkPaint& paint) {
2417 TRACE_EVENT0("skia", TRACE_FUNC);
2418 if (slug) {
2419 this->onDrawSlug(slug, paint);
2420 }
2421 }
2422
onDrawSlug(const Slug * slug,const SkPaint & paint)2423 void SkCanvas::onDrawSlug(const Slug* slug, const SkPaint& paint) {
2424 SkRect bounds = slug->sourceBoundsWithOrigin();
2425 if (this->internalQuickReject(bounds, paint)) {
2426 return;
2427 }
2428 // See comment in onDrawGlyphRunList()
2429 auto layer = this->aboutToDraw(paint, &bounds, PredrawFlags::kSkipMaskFilterAutoLayer);
2430 if (layer) {
2431 this->topDevice()->drawSlug(this, slug, layer->paint());
2432 }
2433 }
2434
2435 // These call the (virtual) onDraw... method
drawSimpleText(const void * text,size_t byteLength,SkTextEncoding encoding,SkScalar x,SkScalar y,const SkFont & font,const SkPaint & paint)2436 void SkCanvas::drawSimpleText(const void* text, size_t byteLength, SkTextEncoding encoding,
2437 SkScalar x, SkScalar y, const SkFont& font, const SkPaint& paint) {
2438 TRACE_EVENT0("skia", TRACE_FUNC);
2439 if (byteLength) {
2440 sk_msan_assert_initialized(text, SkTAddOffset<const void>(text, byteLength));
2441 const sktext::GlyphRunList& glyphRunList =
2442 fScratchGlyphRunBuilder->textToGlyphRunList(
2443 font, paint, text, byteLength, {x, y}, encoding);
2444 if (!glyphRunList.empty()) {
2445 this->onDrawGlyphRunList(glyphRunList, paint);
2446 }
2447 }
2448 }
2449
drawGlyphs(int count,const SkGlyphID * glyphs,const SkPoint * positions,const uint32_t * clusters,int textByteCount,const char * utf8text,SkPoint origin,const SkFont & font,const SkPaint & paint)2450 void SkCanvas::drawGlyphs(int count, const SkGlyphID* glyphs, const SkPoint* positions,
2451 const uint32_t* clusters, int textByteCount, const char* utf8text,
2452 SkPoint origin, const SkFont& font, const SkPaint& paint) {
2453 if (count <= 0) { return; }
2454
2455 sktext::GlyphRun glyphRun {
2456 font,
2457 SkSpan(positions, count),
2458 SkSpan(glyphs, count),
2459 SkSpan(utf8text, textByteCount),
2460 SkSpan(clusters, count),
2461 SkSpan<SkVector>()
2462 };
2463
2464 sktext::GlyphRunList glyphRunList = fScratchGlyphRunBuilder->makeGlyphRunList(
2465 glyphRun, paint, origin);
2466 this->onDrawGlyphRunList(glyphRunList, paint);
2467 }
2468
drawGlyphs(int count,const SkGlyphID glyphs[],const SkPoint positions[],SkPoint origin,const SkFont & font,const SkPaint & paint)2469 void SkCanvas::drawGlyphs(int count, const SkGlyphID glyphs[], const SkPoint positions[],
2470 SkPoint origin, const SkFont& font, const SkPaint& paint) {
2471 if (count <= 0) { return; }
2472
2473 sktext::GlyphRun glyphRun {
2474 font,
2475 SkSpan(positions, count),
2476 SkSpan(glyphs, count),
2477 SkSpan<const char>(),
2478 SkSpan<const uint32_t>(),
2479 SkSpan<SkVector>()
2480 };
2481
2482 sktext::GlyphRunList glyphRunList = fScratchGlyphRunBuilder->makeGlyphRunList(
2483 glyphRun, paint, origin);
2484 this->onDrawGlyphRunList(glyphRunList, paint);
2485 }
2486
drawGlyphs(int count,const SkGlyphID glyphs[],const SkRSXform xforms[],SkPoint origin,const SkFont & font,const SkPaint & paint)2487 void SkCanvas::drawGlyphs(int count, const SkGlyphID glyphs[], const SkRSXform xforms[],
2488 SkPoint origin, const SkFont& font, const SkPaint& paint) {
2489 if (count <= 0) { return; }
2490
2491 auto [positions, rotateScales] =
2492 fScratchGlyphRunBuilder->convertRSXForm(SkSpan(xforms, count));
2493
2494 sktext::GlyphRun glyphRun {
2495 font,
2496 positions,
2497 SkSpan(glyphs, count),
2498 SkSpan<const char>(),
2499 SkSpan<const uint32_t>(),
2500 rotateScales
2501 };
2502 sktext::GlyphRunList glyphRunList = fScratchGlyphRunBuilder->makeGlyphRunList(
2503 glyphRun, paint, origin);
2504 this->onDrawGlyphRunList(glyphRunList, paint);
2505 }
2506
drawTextBlob(const SkTextBlob * blob,SkScalar x,SkScalar y,const SkPaint & paint)2507 void SkCanvas::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
2508 const SkPaint& paint) {
2509 TRACE_EVENT0("skia", TRACE_FUNC);
2510 RETURN_ON_NULL(blob);
2511 RETURN_ON_FALSE(blob->bounds().makeOffset(x, y).isFinite());
2512
2513 // Overflow if more than 2^21 glyphs stopping a buffer overflow latter in the stack.
2514 // See chromium:1080481
2515 // TODO: can consider unrolling a few at a time if this limit becomes a problem.
2516 int totalGlyphCount = 0;
2517 constexpr int kMaxGlyphCount = 1 << 21;
2518 SkTextBlob::Iter i(*blob);
2519 SkTextBlob::Iter::Run r;
2520 while (i.next(&r)) {
2521 int glyphsLeft = kMaxGlyphCount - totalGlyphCount;
2522 RETURN_ON_FALSE(r.fGlyphCount <= glyphsLeft);
2523 totalGlyphCount += r.fGlyphCount;
2524 }
2525
2526 this->onDrawTextBlob(blob, x, y, paint);
2527 }
2528
onDrawVerticesObject(const SkVertices * vertices,SkBlendMode bmode,const SkPaint & paint)2529 void SkCanvas::onDrawVerticesObject(const SkVertices* vertices, SkBlendMode bmode,
2530 const SkPaint& paint) {
2531 SkPaint simplePaint = clean_paint_for_drawVertices(paint);
2532
2533 const SkRect& bounds = vertices->bounds();
2534 if (this->internalQuickReject(bounds, simplePaint)) {
2535 return;
2536 }
2537
2538 auto layer = this->aboutToDraw(simplePaint, &bounds);
2539 if (layer) {
2540 this->topDevice()->drawVertices(vertices, SkBlender::Mode(bmode), layer->paint());
2541 }
2542 }
2543
onDrawMesh(const SkMesh & mesh,sk_sp<SkBlender> blender,const SkPaint & paint)2544 void SkCanvas::onDrawMesh(const SkMesh& mesh, sk_sp<SkBlender> blender, const SkPaint& paint) {
2545 SkPaint simplePaint = clean_paint_for_drawVertices(paint);
2546 auto layer = this->aboutToDraw(simplePaint, nullptr);
2547 if (layer) {
2548 this->topDevice()->drawMesh(mesh, std::move(blender), paint);
2549 }
2550 }
2551
drawPatch(const SkPoint cubics[12],const SkColor colors[4],const SkPoint texCoords[4],SkBlendMode bmode,const SkPaint & paint)2552 void SkCanvas::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
2553 const SkPoint texCoords[4], SkBlendMode bmode,
2554 const SkPaint& paint) {
2555 TRACE_EVENT0("skia", TRACE_FUNC);
2556 if (nullptr == cubics) {
2557 return;
2558 }
2559
2560 this->onDrawPatch(cubics, colors, texCoords, bmode, paint);
2561 }
2562
onDrawPatch(const SkPoint cubics[12],const SkColor colors[4],const SkPoint texCoords[4],SkBlendMode bmode,const SkPaint & paint)2563 void SkCanvas::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
2564 const SkPoint texCoords[4], SkBlendMode bmode,
2565 const SkPaint& paint) {
2566 // drawPatch has the same behavior restrictions as drawVertices
2567 SkPaint simplePaint = clean_paint_for_drawVertices(paint);
2568
2569 // Since a patch is always within the convex hull of the control points, we discard it when its
2570 // bounding rectangle is completely outside the current clip.
2571 SkRect bounds;
2572 bounds.setBounds(cubics, SkPatchUtils::kNumCtrlPts);
2573 if (this->internalQuickReject(bounds, simplePaint)) {
2574 return;
2575 }
2576
2577 auto layer = this->aboutToDraw(simplePaint, &bounds);
2578 if (layer) {
2579 this->topDevice()->drawPatch(cubics, colors, texCoords, SkBlender::Mode(bmode),
2580 layer->paint());
2581 }
2582 }
2583
drawDrawable(SkDrawable * dr,SkScalar x,SkScalar y)2584 void SkCanvas::drawDrawable(SkDrawable* dr, SkScalar x, SkScalar y) {
2585 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
2586 TRACE_EVENT0("skia", TRACE_FUNC);
2587 #endif
2588 RETURN_ON_NULL(dr);
2589 if (x || y) {
2590 SkMatrix matrix = SkMatrix::Translate(x, y);
2591 this->onDrawDrawable(dr, &matrix);
2592 } else {
2593 this->onDrawDrawable(dr, nullptr);
2594 }
2595 }
2596
drawDrawable(SkDrawable * dr,const SkMatrix * matrix)2597 void SkCanvas::drawDrawable(SkDrawable* dr, const SkMatrix* matrix) {
2598 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
2599 TRACE_EVENT0("skia", TRACE_FUNC);
2600 #endif
2601 RETURN_ON_NULL(dr);
2602 if (matrix && matrix->isIdentity()) {
2603 matrix = nullptr;
2604 }
2605 this->onDrawDrawable(dr, matrix);
2606 }
2607
onDrawDrawable(SkDrawable * dr,const SkMatrix * matrix)2608 void SkCanvas::onDrawDrawable(SkDrawable* dr, const SkMatrix* matrix) {
2609 // drawable bounds are no longer reliable (e.g. android displaylist)
2610 // so don't use them for quick-reject
2611 if (this->predrawNotify()) {
2612 this->topDevice()->drawDrawable(this, dr, matrix);
2613 }
2614 }
2615
onDrawAtlas2(const SkImage * atlas,const SkRSXform xform[],const SkRect tex[],const SkColor colors[],int count,SkBlendMode bmode,const SkSamplingOptions & sampling,const SkRect * cull,const SkPaint * paint)2616 void SkCanvas::onDrawAtlas2(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
2617 const SkColor colors[], int count, SkBlendMode bmode,
2618 const SkSamplingOptions& sampling, const SkRect* cull,
2619 const SkPaint* paint) {
2620 // drawAtlas is a combination of drawVertices and drawImage...
2621 SkPaint realPaint = clean_paint_for_drawVertices(clean_paint_for_drawImage(paint));
2622 realPaint.setShader(atlas->makeShader(sampling));
2623
2624 if (cull && this->internalQuickReject(*cull, realPaint)) {
2625 return;
2626 }
2627
2628 // drawAtlas should not have mask filters on its paint, so we don't need to worry about
2629 // converting its "drawImage" behavior into the paint to work with the auto-mask-filter system.
2630 SkASSERT(!realPaint.getMaskFilter());
2631 auto layer = this->aboutToDraw(realPaint);
2632 if (layer) {
2633 this->topDevice()->drawAtlas(xform, tex, colors, count, SkBlender::Mode(bmode),
2634 layer->paint());
2635 }
2636 }
2637
onDrawAnnotation(const SkRect & rect,const char key[],SkData * value)2638 void SkCanvas::onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
2639 SkASSERT(key);
2640
2641 if (this->predrawNotify()) {
2642 this->topDevice()->drawAnnotation(rect, key, value);
2643 }
2644 }
2645
onDrawEdgeAAQuad(const SkRect & r,const SkPoint clip[4],QuadAAFlags edgeAA,const SkColor4f & color,SkBlendMode mode)2646 void SkCanvas::onDrawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], QuadAAFlags edgeAA,
2647 const SkColor4f& color, SkBlendMode mode) {
2648 SkASSERT(r.isSorted());
2649
2650 SkPaint paint{color};
2651 paint.setBlendMode(mode);
2652 if (this->internalQuickReject(r, paint)) {
2653 return;
2654 }
2655
2656 if (this->predrawNotify()) {
2657 this->topDevice()->drawEdgeAAQuad(r, clip, edgeAA, color, mode);
2658 }
2659 }
2660
onDrawEdgeAAImageSet2(const ImageSetEntry imageSet[],int count,const SkPoint dstClips[],const SkMatrix preViewMatrices[],const SkSamplingOptions & sampling,const SkPaint * paint,SrcRectConstraint constraint)2661 void SkCanvas::onDrawEdgeAAImageSet2(const ImageSetEntry imageSet[], int count,
2662 const SkPoint dstClips[], const SkMatrix preViewMatrices[],
2663 const SkSamplingOptions& sampling, const SkPaint* paint,
2664 SrcRectConstraint constraint) {
2665 if (count <= 0) {
2666 // Nothing to draw
2667 return;
2668 }
2669
2670 SkPaint realPaint = clean_paint_for_drawImage(paint);
2671 SkSamplingOptions realSampling = clean_sampling_for_constraint(sampling, constraint);
2672
2673 // We could calculate the set's dstRect union to always check quickReject(), but we can't reject
2674 // individual entries and Chromium's occlusion culling already makes it likely that at least one
2675 // entry will be visible. So, we only calculate the draw bounds when it's trivial (count == 1),
2676 // or we need it for the autolooper (since it greatly improves image filter perf).
2677 bool needsAutoLayer = SkToBool(realPaint.getImageFilter());
2678 bool setBoundsValid = count == 1 || needsAutoLayer;
2679 SkRect setBounds = imageSet[0].fDstRect;
2680 if (imageSet[0].fMatrixIndex >= 0) {
2681 // Account for the per-entry transform that is applied prior to the CTM when drawing
2682 preViewMatrices[imageSet[0].fMatrixIndex].mapRect(&setBounds);
2683 }
2684 if (needsAutoLayer) {
2685 for (int i = 1; i < count; ++i) {
2686 SkRect entryBounds = imageSet[i].fDstRect;
2687 if (imageSet[i].fMatrixIndex >= 0) {
2688 preViewMatrices[imageSet[i].fMatrixIndex].mapRect(&entryBounds);
2689 }
2690 setBounds.joinPossiblyEmptyRect(entryBounds);
2691 }
2692 }
2693
2694 // If we happen to have the draw bounds, though, might as well check quickReject().
2695 if (setBoundsValid && this->internalQuickReject(setBounds, realPaint)) {
2696 return;
2697 }
2698
2699 auto layer = this->aboutToDraw(realPaint, setBoundsValid ? &setBounds : nullptr);
2700 if (layer) {
2701 this->topDevice()->drawEdgeAAImageSet(imageSet, count, dstClips, preViewMatrices,
2702 realSampling, layer->paint(), constraint);
2703 }
2704 }
2705
2706 //////////////////////////////////////////////////////////////////////////////
2707 // These methods are NOT virtual, and therefore must call back into virtual
2708 // methods, rather than actually drawing themselves.
2709 //////////////////////////////////////////////////////////////////////////////
2710
drawColor(const SkColor4f & c,SkBlendMode mode)2711 void SkCanvas::drawColor(const SkColor4f& c, SkBlendMode mode) {
2712 SkPaint paint;
2713 paint.setColor(c);
2714 paint.setBlendMode(mode);
2715 this->drawPaint(paint);
2716 }
2717
drawPoint(SkScalar x,SkScalar y,const SkPaint & paint)2718 void SkCanvas::drawPoint(SkScalar x, SkScalar y, const SkPaint& paint) {
2719 const SkPoint pt = { x, y };
2720 this->drawPoints(kPoints_PointMode, 1, &pt, paint);
2721 }
2722
drawLine(SkScalar x0,SkScalar y0,SkScalar x1,SkScalar y1,const SkPaint & paint)2723 void SkCanvas::drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1, const SkPaint& paint) {
2724 SkPoint pts[2];
2725 pts[0].set(x0, y0);
2726 pts[1].set(x1, y1);
2727 this->drawPoints(kLines_PointMode, 2, pts, paint);
2728 }
2729
drawCircle(SkScalar cx,SkScalar cy,SkScalar radius,const SkPaint & paint)2730 void SkCanvas::drawCircle(SkScalar cx, SkScalar cy, SkScalar radius, const SkPaint& paint) {
2731 if (radius < 0) {
2732 radius = 0;
2733 }
2734
2735 SkRect r;
2736 r.setLTRB(cx - radius, cy - radius, cx + radius, cy + radius);
2737 this->drawOval(r, paint);
2738 }
2739
drawRoundRect(const SkRect & r,SkScalar rx,SkScalar ry,const SkPaint & paint)2740 void SkCanvas::drawRoundRect(const SkRect& r, SkScalar rx, SkScalar ry,
2741 const SkPaint& paint) {
2742 if (rx > 0 && ry > 0) {
2743 SkRRect rrect;
2744 rrect.setRectXY(r, rx, ry);
2745 this->drawRRect(rrect, paint);
2746 } else {
2747 this->drawRect(r, paint);
2748 }
2749 }
2750
drawArc(const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const SkPaint & paint)2751 void SkCanvas::drawArc(const SkRect& oval, SkScalar startAngle,
2752 SkScalar sweepAngle, bool useCenter,
2753 const SkPaint& paint) {
2754 TRACE_EVENT0("skia", TRACE_FUNC);
2755 if (oval.isEmpty() || !sweepAngle) {
2756 return;
2757 }
2758 this->onDrawArc(oval, startAngle, sweepAngle, useCenter, paint);
2759 }
2760
2761 ///////////////////////////////////////////////////////////////////////////////
2762 #ifdef SK_DISABLE_SKPICTURE
drawPicture(const SkPicture * picture,const SkMatrix * matrix,const SkPaint * paint)2763 void SkCanvas::drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {}
2764
2765
onDrawPicture(const SkPicture * picture,const SkMatrix * matrix,const SkPaint * paint)2766 void SkCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
2767 const SkPaint* paint) {}
2768 #else
2769
drawPicture(const SkPicture * picture,const SkMatrix * matrix,const SkPaint * paint)2770 void SkCanvas::drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {
2771 TRACE_EVENT0("skia", TRACE_FUNC);
2772 RETURN_ON_NULL(picture);
2773
2774 if (matrix && matrix->isIdentity()) {
2775 matrix = nullptr;
2776 }
2777 if (picture->approximateOpCount() <= kMaxPictureOpsToUnrollInsteadOfRef) {
2778 SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
2779 picture->playback(this);
2780 } else {
2781 this->onDrawPicture(picture, matrix, paint);
2782 }
2783 }
2784
onDrawPicture(const SkPicture * picture,const SkMatrix * matrix,const SkPaint * paint)2785 void SkCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
2786 const SkPaint* paint) {
2787 if (this->internalQuickReject(picture->cullRect(), paint ? *paint : SkPaint{}, matrix)) {
2788 return;
2789 }
2790
2791 SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
2792 picture->playback(this);
2793 }
2794 #endif
2795
2796 ///////////////////////////////////////////////////////////////////////////////
2797
2798 SkCanvas::ImageSetEntry::ImageSetEntry() = default;
2799 SkCanvas::ImageSetEntry::~ImageSetEntry() = default;
2800 SkCanvas::ImageSetEntry::ImageSetEntry(const ImageSetEntry&) = default;
2801 SkCanvas::ImageSetEntry& SkCanvas::ImageSetEntry::operator=(const ImageSetEntry&) = default;
2802
ImageSetEntry(sk_sp<const SkImage> image,const SkRect & srcRect,const SkRect & dstRect,int matrixIndex,float alpha,unsigned aaFlags,bool hasClip)2803 SkCanvas::ImageSetEntry::ImageSetEntry(sk_sp<const SkImage> image, const SkRect& srcRect,
2804 const SkRect& dstRect, int matrixIndex, float alpha,
2805 unsigned aaFlags, bool hasClip)
2806 : fImage(std::move(image))
2807 , fSrcRect(srcRect)
2808 , fDstRect(dstRect)
2809 , fMatrixIndex(matrixIndex)
2810 , fAlpha(alpha)
2811 , fAAFlags(aaFlags)
2812 , fHasClip(hasClip) {}
2813
ImageSetEntry(sk_sp<const SkImage> image,const SkRect & srcRect,const SkRect & dstRect,float alpha,unsigned aaFlags)2814 SkCanvas::ImageSetEntry::ImageSetEntry(sk_sp<const SkImage> image, const SkRect& srcRect,
2815 const SkRect& dstRect, float alpha, unsigned aaFlags)
2816 : fImage(std::move(image))
2817 , fSrcRect(srcRect)
2818 , fDstRect(dstRect)
2819 , fAlpha(alpha)
2820 , fAAFlags(aaFlags) {}
2821
2822 ///////////////////////////////////////////////////////////////////////////////
2823
MakeRasterDirect(const SkImageInfo & info,void * pixels,size_t rowBytes,const SkSurfaceProps * props)2824 std::unique_ptr<SkCanvas> SkCanvas::MakeRasterDirect(const SkImageInfo& info, void* pixels,
2825 size_t rowBytes, const SkSurfaceProps* props) {
2826 if (!SkSurfaceValidateRasterInfo(info, rowBytes)) {
2827 return nullptr;
2828 }
2829
2830 SkBitmap bitmap;
2831 if (!bitmap.installPixels(info, pixels, rowBytes)) {
2832 return nullptr;
2833 }
2834
2835 return props ?
2836 std::make_unique<SkCanvas>(bitmap, *props) :
2837 std::make_unique<SkCanvas>(bitmap);
2838 }
2839
2840 ///////////////////////////////////////////////////////////////////////////////
2841
SkNoDrawCanvas(int width,int height)2842 SkNoDrawCanvas::SkNoDrawCanvas(int width, int height)
2843 : INHERITED(SkIRect::MakeWH(width, height)) {}
2844
SkNoDrawCanvas(const SkIRect & bounds)2845 SkNoDrawCanvas::SkNoDrawCanvas(const SkIRect& bounds)
2846 : INHERITED(bounds) {}
2847
getSaveLayerStrategy(const SaveLayerRec & rec)2848 SkCanvas::SaveLayerStrategy SkNoDrawCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {
2849 (void)this->INHERITED::getSaveLayerStrategy(rec);
2850 return kNoLayer_SaveLayerStrategy;
2851 }
2852
onDoSaveBehind(const SkRect *)2853 bool SkNoDrawCanvas::onDoSaveBehind(const SkRect*) {
2854 return false;
2855 }
2856
2857 ///////////////////////////////////////////////////////////////////////////////
2858
2859 static_assert((int)SkRegion::kDifference_Op == (int)SkClipOp::kDifference, "");
2860 static_assert((int)SkRegion::kIntersect_Op == (int)SkClipOp::kIntersect, "");
2861
2862 ///////////////////////////////////////////////////////////////////////////////////////////////////
2863
accessTopRasterHandle() const2864 SkRasterHandleAllocator::Handle SkCanvas::accessTopRasterHandle() const {
2865 const SkDevice* dev = this->topDevice();
2866 if (fAllocator) {
2867 SkRasterHandleAllocator::Handle handle = dev->getRasterHandle();
2868 SkIRect clip = dev->devClipBounds();
2869 if (!clip.intersect({0, 0, dev->width(), dev->height()})) {
2870 clip.setEmpty();
2871 }
2872
2873 fAllocator->updateHandle(handle, dev->localToDevice(), clip);
2874 return handle;
2875 }
2876 return nullptr;
2877 }
2878
install(SkBitmap * bm,const SkImageInfo & info,const SkRasterHandleAllocator::Rec & rec)2879 static bool install(SkBitmap* bm, const SkImageInfo& info,
2880 const SkRasterHandleAllocator::Rec& rec) {
2881 return bm->installPixels(info, rec.fPixels, rec.fRowBytes, rec.fReleaseProc, rec.fReleaseCtx);
2882 }
2883
allocBitmap(const SkImageInfo & info,SkBitmap * bm)2884 SkRasterHandleAllocator::Handle SkRasterHandleAllocator::allocBitmap(const SkImageInfo& info,
2885 SkBitmap* bm) {
2886 SkRasterHandleAllocator::Rec rec;
2887 if (!this->allocHandle(info, &rec) || !install(bm, info, rec)) {
2888 return nullptr;
2889 }
2890 return rec.fHandle;
2891 }
2892
2893 std::unique_ptr<SkCanvas>
MakeCanvas(std::unique_ptr<SkRasterHandleAllocator> alloc,const SkImageInfo & info,const Rec * rec,const SkSurfaceProps * props)2894 SkRasterHandleAllocator::MakeCanvas(std::unique_ptr<SkRasterHandleAllocator> alloc,
2895 const SkImageInfo& info, const Rec* rec,
2896 const SkSurfaceProps* props) {
2897 if (!alloc || !SkSurfaceValidateRasterInfo(info, rec ? rec->fRowBytes : kIgnoreRowBytesValue)) {
2898 return nullptr;
2899 }
2900
2901 SkBitmap bm;
2902 Handle hndl;
2903
2904 if (rec) {
2905 hndl = install(&bm, info, *rec) ? rec->fHandle : nullptr;
2906 } else {
2907 hndl = alloc->allocBitmap(info, &bm);
2908 }
2909 return hndl ? std::unique_ptr<SkCanvas>(new SkCanvas(bm, std::move(alloc), hndl, props))
2910 : nullptr;
2911 }
2912