Debian Codegraph @

src/core/SkCanvas.cpp

raw
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/SkLatticeIter.h"
54 #include "src/core/SkMaskFilterBase.h"
55 #include "src/core/SkMatrixPriv.h"
56 #include "src/core/SkPaintPriv.h"
57 #include "src/core/SkSpecialImage.h"
58 #include "src/core/SkSurfacePriv.h"
59 #include "src/core/SkTraceEvent.h"
60 #include "src/core/SkVerticesPriv.h"
61 #include "src/effects/colorfilters/SkColorFilterBase.h"
62 #include "src/image/SkSurface_Base.h"
63 #include "src/shaders/SkImageShader.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
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
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
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
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
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
203 SkCanvas::MCRec::MCRec(SkDevice* device) : fDevice(device) {
204 SkASSERT(fDevice);
205 }
206
207 SkCanvas::MCRec::MCRec(const MCRec* prev) : fDevice(prev->fDevice), fMatrix(prev->fMatrix) {
208 SkASSERT(fDevice);
209 }
210
211 SkCanvas::MCRec::~MCRec() {}
212
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
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:
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 }
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
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
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
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
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
325 SkCanvas::SkCanvas() : fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage)) {
326 this->init(nullptr);
327 }
328
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
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
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
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
366 SkSurface* SkCanvas::getSurface() const {
367 return fSurfaceBase;
368 }
369
370 SkISize SkCanvas::getBaseLayerSize() const {
371 return this->rootDevice()->imageInfo().dimensions();
372 }
373
374 SkDevice* SkCanvas::topDevice() const {
375 SkASSERT(fMCRec->fDevice);
376 return fMCRec->fDevice;
377 }
378
379 bool SkCanvas::readPixels(const SkPixmap& pm, int x, int y) {
380 return pm.addr() && this->rootDevice()->readPixels(pm, x, y);
381 }
382
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
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
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
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
426 void SkCanvas::checkForDeferredSave() {
427 if (fMCRec->fDeferredSaveCount > 0) {
428 this->doSave();
429 }
430 }
431
432 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
448 int SkCanvas::save() {
449 fSaveCount += 1;
450 fMCRec->fDeferredSaveCount += 1;
451 return this->getSaveCount() - 1; // return our prev value
452 }
453
454 void SkCanvas::doSave() {
455 this->willSave();
456
457 SkASSERT(fMCRec->fDeferredSaveCount > 0);
458 fMCRec->fDeferredSaveCount -= 1;
459 this->internalSave();
460 }
461
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
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
491 void SkCanvas::internalSave() {
492 fMCRec = new (fMCStack.push_back()) MCRec(fMCRec);
493
494 this->topDevice()->pushClipStack();
495 }
496
497 int SkCanvas::saveLayer(const SkRect* bounds, const SkPaint* paint) {
498 return this->saveLayer(SaveLayerRec(bounds, paint, 0));
499 }
500
501 int SkCanvas::saveLayer(const SaveLayerRec& rec) {
502 TRACE_EVENT0("skia", TRACE_FUNC);
503 if (rec.fPaint && this->nothingToDraw(*rec.fPaint)) {
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
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.
533 static skif::ParameterSpace<SkPoint> compute_decomposition_center(
534 const SkM44& 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 SkV4 mappedCenter = dstToLocal.map(center.fX, center.fY, 0.f, 1.f);
544 center = {sk_ieee_float_divide(mappedCenter.x, mappedCenter.w),
545 sk_ieee_float_divide(mappedCenter.y, mappedCenter.w)};
546 }
547
548 return skif::ParameterSpace<SkPoint>(center);
549 }
550
551 // Helper when we need to upgrade a single filter to a FilterSpan
552 struct FilterToSpan {
553 FilterToSpan(const SkImageFilter* filter) : fFilter(sk_ref_sp(filter)) {}
554
555 operator SkCanvas::FilterSpan() {
556 return fFilter ? SkCanvas::FilterSpan{&fFilter, 1} : SkCanvas::FilterSpan{};
557 }
558
559 sk_sp<SkImageFilter> fFilter;
560 };
561
562 // Compute suitable transformations and layer bounds for a new layer that will be used as the source
563 // input into 'filter' before being drawn into 'dst' via the returned skif::Mapping.
564 // Null filters are permitted and act as the identity. The returned mapping will be compatible with
565 // the image filter.
566 //
567 // An empty optional is returned if the layer mapping and bounds couldn't be determined, in which
568 // case the layer should be skipped. An instantiated optional can have an empty layer bounds rect
569 // if the image filter doesn't require an input image to produce a valid output.
570 static std::optional<std::pair<skif::Mapping, skif::LayerSpace<SkIRect>>>
571 get_layer_mapping_and_bounds(
572 SkCanvas::FilterSpan filters,
573 const SkM44& localToDst,
574 const skif::DeviceSpace<SkIRect>& targetOutput,
575 std::optional<skif::ParameterSpace<SkRect>> contentBounds = {},
576 SkScalar scaleFactor = 1.0f) {
577 SkM44 dstToLocal;
578 if (!localToDst.isFinite() ||
579 !localToDst.invert(&dstToLocal)) {
580 return {};
581 }
582
583 skif::ParameterSpace<SkPoint> center =
584 compute_decomposition_center(dstToLocal, contentBounds, targetOutput);
585
586 // Determine initial mapping and a reasonable maximum dimension to prevent layer-to-device
587 // transforms with perspective and skew from triggering excessive buffer allocations.
588 skif::Mapping mapping;
589 skif::MatrixCapability capability = skif::MatrixCapability::kComplex;
590 for (const sk_sp<SkImageFilter>& filter : filters) {
591 if (filter) {
592 capability = std::min(capability, as_IFB(filter)->getCTMCapability());
593 }
594 }
595 if (!mapping.decomposeCTM(localToDst, capability, center)) {
596 return {};
597 }
598 // Push scale factor into layer matrix and device matrix (net no change, but the layer will have
599 // its resolution adjusted in comparison to the final device).
600 if (scaleFactor != 1.0f &&
601 !mapping.adjustLayerSpace(SkM44::Scale(scaleFactor, scaleFactor))) {
602 return {};
603 }
604
605 // Perspective and skew could exceed this since mapping.deviceToLayer(targetOutput) is
606 // theoretically unbounded under those conditions. Under a 45 degree rotation, a layer needs to
607 // be 2X larger per side of the prior device in order to fully cover it. We use the max of that
608 // and 2048 for a reasonable upper limit (this allows small layers under extreme transforms to
609 // use more relative resolution than a larger layer).
610 static const int kMinDimThreshold = 2048;
611 int maxLayerDim = std::max(Sk64_pin_to_s32(2 * std::max(SkIRect(targetOutput).width64(),
612 SkIRect(targetOutput).height64())),
613 kMinDimThreshold);
614
615 auto baseLayerBounds = mapping.deviceToLayer(targetOutput);
616 if (contentBounds) {
617 // For better or for worse, user bounds currently act as a hard clip on the layer's
618 // extent (i.e., they implement the CSS filter-effects 'filter region' feature).
619 skif::LayerSpace<SkIRect> knownBounds = mapping.paramToLayer(*contentBounds).roundOut();
620 if (!baseLayerBounds.intersect(knownBounds)) {
621 baseLayerBounds = skif::LayerSpace<SkIRect>::Empty();
622 }
623 }
624
625 skif::LayerSpace<SkIRect> layerBounds;
626 if (!filters.empty()) {
627 layerBounds = skif::LayerSpace<SkIRect>::Union(filters.size(), [&](int i) {
628 return filters[i] ? as_IFB(filters[i])
629 ->getInputBounds(mapping, targetOutput, contentBounds)
630 : baseLayerBounds;
631 });
632 // When a filter is involved, the layer size may be larger than the default maxLayerDim due
633 // to required inputs for filters (e.g. a displacement map with a large radius).
634 if (layerBounds.width() > maxLayerDim || layerBounds.height() > maxLayerDim) {
635 skif::Mapping idealMapping{mapping.layerMatrix()};
636 for (const sk_sp<SkImageFilter>& filter : filters) {
637 if (filter) {
638 auto idealLayerBounds = as_IFB(filter)->getInputBounds(
639 idealMapping, targetOutput, contentBounds);
640 maxLayerDim = std::max(std::max(idealLayerBounds.width(),
641 idealLayerBounds.height()),
642 maxLayerDim);
643 }
644 }
645 }
646 } else {
647 if (baseLayerBounds.isEmpty()) {
648 return {};
649 }
650 layerBounds = baseLayerBounds;
651 }
652
653 if (layerBounds.width() > maxLayerDim || layerBounds.height() > maxLayerDim) {
654 skif::LayerSpace<SkIRect> newLayerBounds(
655 SkIRect::MakeWH(std::min(layerBounds.width(), maxLayerDim),
656 std::min(layerBounds.height(), maxLayerDim)));
657 SkM44 adjust = SkM44::RectToRect(SkRect::Make(SkIRect(layerBounds)),
658 SkRect::Make(SkIRect(newLayerBounds)));
659 if (!mapping.adjustLayerSpace(adjust)) {
660 return {};
661 } else {
662 layerBounds = newLayerBounds;
663 }
664 }
665
666 return std::make_pair(mapping, layerBounds);
667 }
668
669 // Ideally image filters operate in the dst color type, but if there is insufficient alpha bits
670 // we move some bits from color channels into the alpha channel since that can greatly improve
671 // the quality of blurs and other filters.
672 static SkColorType image_filter_color_type(const SkColorInfo& dstInfo) {
673 if (dstInfo.bytesPerPixel() <= 4 &&
674 dstInfo.colorType() != kRGBA_8888_SkColorType &&
675 dstInfo.colorType() != kBGRA_8888_SkColorType) {
676 // "Upgrade" A8, G8, 565, 4444, 1010102, 101010x, and 888x to 8888
677 return kN32_SkColorType;
678 } else {
679 return dstInfo.colorType();
680 }
681 }
682
683 static skif::FilterResult apply_alpha_and_colorfilter(const skif::Context& ctx,
684 const skif::FilterResult& image,
685 const SkPaint& paint) {
686 // The only effects that apply to layers (other than the SkImageFilter that made this image in
687 // the first place) are transparency and color filters.
688 skif::FilterResult result = image;
689 if (paint.getAlphaf() < 1.f) {
690 result = result.applyColorFilter(ctx, SkColorFilters::Blend(paint.getColor4f(),
691 /*colorSpace=*/nullptr,
692 SkBlendMode::kDstIn));
693 }
694 if (paint.getColorFilter()) {
695 result = result.applyColorFilter(ctx, paint.refColorFilter());
696 }
697 return result;
698 }
699
700 void SkCanvas::internalDrawDeviceWithFilter(SkDevice* src,
701 SkDevice* dst,
702 FilterSpan filters,
703 const SkPaint& paint,
704 DeviceCompatibleWithFilter compat,
705 const SkColorInfo& filterColorInfo,
706 SkScalar scaleFactor,
707 SkTileMode srcTileMode,
708 bool srcIsCoverageLayer) {
709 // The dst is always required, the src can be null if 'filter' is non-null and does not require
710 // a source image. For regular filters, 'src' is the layer and 'dst' is the parent device. For
711 // backdrop filters, 'src' is the parent device and 'dst' is the layer.
712 SkASSERT(dst);
713
714 sk_sp<SkColorSpace> filterColorSpace = filterColorInfo.refColorSpace();
715
716 const SkColorType filterColorType =
717 srcIsCoverageLayer ? kAlpha_8_SkColorType : image_filter_color_type(filterColorInfo);
718
719 // 'filter' sees the src device's buffer as the implicit input image, and processes the image
720 // in this device space (referred to as the "layer" space). However, the filter
721 // parameters need to respect the current matrix, which is not necessarily the local matrix that
722 // was set on 'src' (e.g. because we've popped src off the stack already).
723 SkM44 localToSrc = src ? (src->globalToDevice() * fMCRec->fMatrix) : SkM44();
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->localToDevice44(), 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 SkM44 srcToLocal;
764 if (!localToSrc.invert(&srcToLocal)) {
765 return;
766 }
767 srcToLayer = skif::LayerSpace<SkMatrix>((mapping.layerMatrix()*srcToLocal).asM33());
768 } // Else no input is needed which can happen if a backdrop filter that doesn't use src
769 } else {
770 // Trust the caller that no input was required, but keep the calculated mapping
771 requiredInput = skif::LayerSpace<SkIRect>::Empty();
772 }
773 }
774
775 // Start out with an empty source image, to be replaced with the snapped 'src' device.
776 auto backend = dst->createImageFilteringBackend(src ? src->surfaceProps() : dst->surfaceProps(),
777 filterColorType);
778 skif::Stats stats;
779 skif::Context ctx{std::move(backend),
780 mapping,
781 requiredInput,
782 skif::FilterResult{},
783 filterColorSpace.get(),
784 &stats};
785
786 skif::FilterResult source;
787 if (src && !requiredInput.isEmpty()) {
788 skif::LayerSpace<SkIRect> srcSubset;
789 if (!srcToLayer.inverseMapRect(requiredInput, &srcSubset)) {
790 return;
791 }
792
793 // Include the layer in the offscreen count
794 ctx.markNewSurface();
795
796 auto availSrc = skif::LayerSpace<SkIRect>(src->size()).relevantSubset(
797 srcSubset, srcTileMode);
798
799 if (SkMatrix(srcToLayer).isScaleTranslate()) {
800 // Apply the srcToLayer transformation directly while snapping an image from the src
801 // device. Calculate the subset of requiredInput that corresponds to srcSubset that was
802 // restricted to the actual src dimensions.
803 auto requiredSubset = srcToLayer.mapRect(availSrc);
804 if (requiredSubset.width() == availSrc.width() &&
805 requiredSubset.height() == availSrc.height()) {
806 // Unlike snapSpecialScaled(), snapSpecial() can avoid a copy when the underlying
807 // representation permits it.
808 source = {src->snapSpecial(SkIRect(availSrc)), requiredSubset.topLeft()};
809 } else {
810 SkASSERT(compat == DeviceCompatibleWithFilter::kUnknown);
811 source = {src->snapSpecialScaled(SkIRect(availSrc),
812 SkISize(requiredSubset.size())),
813 requiredSubset.topLeft()};
814 ctx.markNewSurface();
815 }
816 }
817
818 if (compat == DeviceCompatibleWithFilter::kYesWithPadding) {
819 // Padding was added to the source image when the 'src' SkDevice was created, so inset
820 // to allow bounds tracking to skip shader-based tiling when possible.
821 SkASSERT(!filters.empty());
822 source = source.insetForSaveLayer();
823 } else if (compat == DeviceCompatibleWithFilter::kYes) {
824 // Do nothing, leave `source` as-is; FilterResult will automatically augment the image
825 // sampling as needed to be visually equivalent to the more optimal kYesWithPadding case
826 } else if (source) {
827 // A backdrop filter that succeeded in snapSpecial() or snapSpecialScaled(), but since
828 // the 'src' device wasn't prepared with 'requiredInput' in mind, add clamping.
829 source = source.applyCrop(ctx, source.layerBounds(), srcTileMode);
830 } else if (!requiredInput.isEmpty()) {
831 // Otherwise snapSpecialScaled() failed or the transform was complex, so snap the source
832 // image at its original resolution and then apply srcToLayer to map to the effective
833 // layer coordinate space.
834 source = {src->snapSpecial(SkIRect(availSrc)), availSrc.topLeft()};
835 // We adjust the desired output of the applyCrop() because ctx was original set to
836 // fulfill 'requiredInput', which is valid *after* we apply srcToLayer. Use the original
837 // 'srcSubset' for the desired output so that the tilemode applied to the available
838 // subset is not discarded as a no-op.
839 source = source.applyCrop(ctx.withNewDesiredOutput(srcSubset),
840 source.layerBounds(),
841 srcTileMode)
842 .applyTransform(ctx, srcToLayer, SkFilterMode::kLinear);
843 }
844 } // else leave 'source' as the empty image
845
846 // Evaluate the image filter, with a context pointing to the source snapped from 'src' and
847 // possibly transformed into the intermediate layer coordinate space.
848 ctx = ctx.withNewDesiredOutput(mapping.deviceToLayer(outputBounds))
849 .withNewSource(source);
850
851 // Here, we allow a single-element FilterSpan with a null entry, to simplify the loop:
852 sk_sp<SkImageFilter> nullFilter;
853 FilterSpan filtersOrNull = filters.empty() ? FilterSpan{&nullFilter, 1} : filters;
854
855 for (const sk_sp<SkImageFilter>& filter : filtersOrNull) {
856 auto result = filter ? as_IFB(filter)->filterImage(ctx) : source;
857
858 if (srcIsCoverageLayer) {
859 SkASSERT(dst->useDrawCoverageMaskForMaskFilters());
860 // TODO: Can FilterResult optimize this in any meaningful way if it still has to go
861 // through drawCoverageMask that requires an image (vs a coverage shader)?
862 auto [coverageMask, origin] = result.imageAndOffset(ctx);
863 if (coverageMask) {
864 SkM44 deviceMatrixWithOffset = mapping.layerToDevice();
865 deviceMatrixWithOffset.preTranslate(origin.x(), origin.y());
866 dst->drawCoverageMask(
867 coverageMask.get(), deviceMatrixWithOffset.asM33(),
868 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
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/40042614
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->localToDevice44(), 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() * newLayerMapping.layerToDevice(),
1062 newLayerMapping.deviceToLayer() * priorDevice->globalToDevice(),
1063 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
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
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
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
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
1221 sk_sp<SkSurface> SkCanvas::onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1222 return this->rootDevice()->makeSurface(info, props);
1223 }
1224
1225 SkImageInfo SkCanvas::imageInfo() const {
1226 return this->onImageInfo();
1227 }
1228
1229 SkImageInfo SkCanvas::onImageInfo() const {
1230 return this->rootDevice()->imageInfo();
1231 }
1232
1233 bool SkCanvas::getProps(SkSurfaceProps* props) const {
1234 return this->onGetProps(props, /*top=*/false);
1235 }
1236
1237 SkSurfaceProps SkCanvas::getBaseProps() const {
1238 SkSurfaceProps props;
1239 this->onGetProps(&props, /*top=*/false);
1240 return props;
1241 }
1242
1243 SkSurfaceProps SkCanvas::getTopProps() const {
1244 SkSurfaceProps props;
1245 this->onGetProps(&props, /*top=*/true);
1246 return props;
1247 }
1248
1249 bool SkCanvas::onGetProps(SkSurfaceProps* props, bool top) const {
1250 if (props) {
1251 *props = top ? topDevice()->surfaceProps() : fProps;
1252 }
1253 return true;
1254 }
1255
1256 bool SkCanvas::peekPixels(SkPixmap* pmap) {
1257 return this->onPeekPixels(pmap);
1258 }
1259
1260 bool SkCanvas::onPeekPixels(SkPixmap* pmap) {
1261 return this->rootDevice()->peekPixels(pmap);
1262 }
1263
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
1291 bool SkCanvas::onAccessTopLayerPixels(SkPixmap* pmap) {
1292 return this->topDevice()->accessPixels(pmap);
1293 }
1294
1295 /////////////////////////////////////////////////////////////////////////////
1296
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
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
1319 void SkCanvas::rotate(SkScalar degrees) {
1320 SkMatrix m;
1321 m.setRotate(degrees);
1322 this->concat(m);
1323 }
1324
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
1331 void SkCanvas::skew(SkScalar sx, SkScalar sy) {
1332 SkMatrix m;
1333 m.setSkew(sx, sy);
1334 this->concat(m);
1335 }
1336
1337 void SkCanvas::concat(const SkMatrix& matrix) {
1338 if (matrix.isIdentity()) {
1339 return;
1340 }
1341 this->concat(SkM44(matrix));
1342 }
1343
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
1352 void SkCanvas::concat(const SkM44& m) {
1353 this->internalConcat44(m);
1354 // notify subclasses
1355 this->didConcat44(m);
1356 }
1357
1358 void SkCanvas::internalSetMatrix(const SkM44& m) {
1359 fMCRec->fMatrix = m;
1360
1361 this->topDevice()->setGlobalCTM(fMCRec->fMatrix);
1362 }
1363
1364 void SkCanvas::setMatrix(const SkMatrix& matrix) {
1365 this->setMatrix(SkM44(matrix));
1366 }
1367
1368 void SkCanvas::setMatrix(const SkM44& m) {
1369 this->checkForDeferredSave();
1370 this->internalSetMatrix(m);
1371 this->didSetM44(m);
1372 }
1373
1374 void SkCanvas::resetMatrix() {
1375 this->setMatrix(SkM44());
1376 }
1377
1378 //////////////////////////////////////////////////////////////////////////////
1379
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
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
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/40043342).
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
1438 void SkCanvas::internal_private_resetClip() {
1439 this->checkForDeferredSave();
1440 this->onResetClip();
1441 }
1442
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
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
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
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
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
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
1524 void SkCanvas::onClipShader(sk_sp<SkShader> sh, SkClipOp op) {
1525 AutoUpdateQRBounds aqr(this);
1526 this->topDevice()->clipShader(sh, op);
1527 }
1528
1529 void SkCanvas::clipRegion(const SkRegion& rgn, SkClipOp op) {
1530 this->checkForDeferredSave();
1531 this->onClipRegion(rgn, op);
1532 }
1533
1534 void SkCanvas::onClipRegion(const SkRegion& rgn, SkClipOp op) {
1535 AutoUpdateQRBounds aqr(this);
1536 this->topDevice()->clipRegion(rgn, op);
1537 }
1538
1539 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
1550 bool SkCanvas::androidFramework_isClipAA() const {
1551 return this->topDevice()->isClipAntiAliased();
1552 }
1553
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
1568 bool SkCanvas::isClipEmpty() const {
1569 return this->topDevice()->isClipEmpty();
1570 }
1571
1572 bool SkCanvas::isClipRect() const {
1573 return this->topDevice()->isClipRect();
1574 }
1575
1576 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
1586 bool SkCanvas::quickReject(const SkPath& path) const {
1587 return path.isEmpty() || this->quickReject(path.getBounds());
1588 }
1589
1590 bool SkCanvas::nothingToDraw(const SkPaint& paint) const {
1591 return !this->topDevice()->surfaceProps().preservesTransparentDraws() && paint.nothingToDraw();
1592 }
1593
1594 bool SkCanvas::internalQuickReject(const SkRect& bounds, const SkPaint& paint,
1595 const SkMatrix* matrix) {
1596 if (!bounds.isFinite() || this->nothingToDraw(paint)) {
1597 return true;
1598 }
1599
1600 if (paint.canComputeFastBounds()) {
1601 SkRect tmp = matrix ? matrix->mapRect(bounds) : bounds;
1602 return this->quickReject(paint.computeFastBounds(tmp, &tmp));
1603 }
1604
1605 return false;
1606 }
1607
1608
1609 SkRect SkCanvas::getLocalClipBounds() const {
1610 SkIRect ibounds = this->getDeviceClipBounds();
1611 if (ibounds.isEmpty()) {
1612 return SkRect::MakeEmpty();
1613 }
1614
1615 auto inverse = fMCRec->fMatrix.asM33().invert();
1616 // if we can't invert the CTM, we can't return local clip bounds
1617 if (!inverse) {
1618 return SkRect::MakeEmpty();
1619 }
1620
1621 // adjust it outwards in case we are antialiasing
1622 const int margin = 1;
1623
1624 return inverse->mapRect(SkRect::Make(ibounds.makeOutset(margin, margin)));
1625 }
1626
1627 SkIRect SkCanvas::getDeviceClipBounds() const {
1628 return this->computeDeviceClipBounds(/*outsetForAA=*/false).roundOut();
1629 }
1630
1631 SkRect SkCanvas::computeDeviceClipBounds(bool outsetForAA) const {
1632 const SkDevice* dev = this->topDevice();
1633 if (dev->isClipEmpty()) {
1634 return SkRect::MakeEmpty();
1635 } else {
1636 SkRect devClipBounds =
1637 SkMatrixPriv::MapRect(dev->deviceToGlobal(), SkRect::Make(dev->devClipBounds()));
1638 if (outsetForAA) {
1639 // Expand bounds out by 1 in case we are anti-aliasing. We store the
1640 // bounds as floats to enable a faster quick reject implementation.
1641 devClipBounds.outset(1.f, 1.f);
1642 }
1643 return devClipBounds;
1644 }
1645 }
1646
1647 ///////////////////////////////////////////////////////////////////////
1648
1649 SkMatrix SkCanvas::getTotalMatrix() const {
1650 return fMCRec->fMatrix.asM33();
1651 }
1652
1653 SkM44 SkCanvas::getLocalToDevice() const {
1654 return fMCRec->fMatrix;
1655 }
1656
1657 GrRecordingContext* SkCanvas::recordingContext() const {
1658 return this->topDevice()->recordingContext();
1659 }
1660
1661 skgpu::graphite::Recorder* SkCanvas::recorder() const {
1662 return this->topDevice()->recorder();
1663 }
1664
1665 SkRecorder* SkCanvas::baseRecorder() const {
1666 return this->topDevice()->baseRecorder();
1667 }
1668
1669 void SkCanvas::drawDRRect(const SkRRect& outer, const SkRRect& inner,
1670 const SkPaint& paint) {
1671 TRACE_EVENT0("skia", TRACE_FUNC);
1672 if (outer.isEmpty()) {
1673 return;
1674 }
1675 if (inner.isEmpty()) {
1676 this->drawRRect(outer, paint);
1677 return;
1678 }
1679
1680 // We don't have this method (yet), but technically this is what we should
1681 // be able to return ...
1682 // if (!outer.contains(inner))) {
1683 //
1684 // For now at least check for containment of bounds
1685 if (!outer.getBounds().contains(inner.getBounds())) {
1686 return;
1687 }
1688
1689 this->onDrawDRRect(outer, inner, paint);
1690 }
1691
1692 void SkCanvas::drawPaint(const SkPaint& paint) {
1693 TRACE_EVENT0("skia", TRACE_FUNC);
1694 this->onDrawPaint(paint);
1695 }
1696
1697 void SkCanvas::drawRect(const SkRect& r, const SkPaint& paint) {
1698 TRACE_EVENT0("skia", TRACE_FUNC);
1699 // To avoid redundant logic in our culling code and various backends, we always sort rects
1700 // before passing them along.
1701 this->onDrawRect(r.makeSorted(), paint);
1702 }
1703
1704 void SkCanvas::drawClippedToSaveBehind(const SkPaint& paint) {
1705 TRACE_EVENT0("skia", TRACE_FUNC);
1706 this->onDrawBehind(paint);
1707 }
1708
1709 void SkCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
1710 TRACE_EVENT0("skia", TRACE_FUNC);
1711 if (region.isEmpty()) {
1712 return;
1713 }
1714
1715 if (region.isRect()) {
1716 return this->drawIRect(region.getBounds(), paint);
1717 }
1718
1719 this->onDrawRegion(region, paint);
1720 }
1721
1722 void SkCanvas::drawOval(const SkRect& r, const SkPaint& paint) {
1723 TRACE_EVENT0("skia", TRACE_FUNC);
1724 // To avoid redundant logic in our culling code and various backends, we always sort rects
1725 // before passing them along.
1726 this->onDrawOval(r.makeSorted(), paint);
1727 }
1728
1729 void SkCanvas::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
1730 TRACE_EVENT0("skia", TRACE_FUNC);
1731 this->onDrawRRect(rrect, paint);
1732 }
1733
1734 void SkCanvas::drawPoints(PointMode mode, SkSpan<const SkPoint> pts, const SkPaint& paint) {
1735 TRACE_EVENT0("skia", TRACE_FUNC);
1736 if (!pts.empty()) {
1737 this->onDrawPoints(mode, pts.size(), pts.data(), paint);
1738 }
1739 }
1740
1741 void SkCanvas::drawVertices(const sk_sp<SkVertices>& vertices, SkBlendMode mode,
1742 const SkPaint& paint) {
1743 this->drawVertices(vertices.get(), mode, paint);
1744 }
1745
1746 void SkCanvas::drawVertices(const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint) {
1747 TRACE_EVENT0("skia", TRACE_FUNC);
1748 RETURN_ON_NULL(vertices);
1749
1750 // We expect fans to be converted to triangles when building or deserializing SkVertices.
1751 SkASSERT(vertices->priv().mode() != SkVertices::kTriangleFan_VertexMode);
1752
1753 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1754 // Preserve legacy behavior for Android: ignore the SkShader if there are no texCoords present
1755 if (paint.getShader() && !vertices->priv().hasTexCoords()) {
1756 SkPaint noShaderPaint(paint);
1757 noShaderPaint.setShader(nullptr);
1758 this->onDrawVerticesObject(vertices, mode, noShaderPaint);
1759 return;
1760 }
1761 #endif
1762 this->onDrawVerticesObject(vertices, mode, paint);
1763 }
1764
1765 void SkCanvas::drawMesh(const SkMesh& mesh, sk_sp<SkBlender> blender, const SkPaint& paint) {
1766 TRACE_EVENT0("skia", TRACE_FUNC);
1767 if (!blender) {
1768 blender = SkBlender::Mode(SkBlendMode::kModulate);
1769 }
1770 this->onDrawMesh(mesh, std::move(blender), paint);
1771 }
1772
1773 void SkCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
1774 TRACE_EVENT0("skia", TRACE_FUNC);
1775 this->onDrawPath(path, paint);
1776 }
1777
1778 // Returns true if the rect can be "filled" : non-empty and finite
1779 static bool fillable(const SkRect& r) {
1780 SkScalar w = r.width();
1781 SkScalar h = r.height();
1782 return SkIsFinite(w, h) && w > 0 && h > 0;
1783 }
1784
1785 static SkPaint clean_paint_for_lattice(const SkPaint* paint) {
1786 SkPaint cleaned;
1787 if (paint) {
1788 cleaned = *paint;
1789 cleaned.setMaskFilter(nullptr);
1790 cleaned.setAntiAlias(false);
1791 }
1792 return cleaned;
1793 }
1794
1795 void SkCanvas::drawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
1796 SkFilterMode filter, const SkPaint* paint) {
1797 RETURN_ON_NULL(image);
1798
1799 const int xdivs[] = {center.fLeft, center.fRight};
1800 const int ydivs[] = {center.fTop, center.fBottom};
1801
1802 Lattice lat;
1803 lat.fXDivs = xdivs;
1804 lat.fYDivs = ydivs;
1805 lat.fRectTypes = nullptr;
1806 lat.fXCount = lat.fYCount = 2;
1807 lat.fBounds = nullptr;
1808 lat.fColors = nullptr;
1809 this->drawImageLattice(image, lat, dst, filter, paint);
1810 }
1811
1812 void SkCanvas::drawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
1813 SkFilterMode filter, const SkPaint* paint) {
1814 TRACE_EVENT0("skia", TRACE_FUNC);
1815 RETURN_ON_NULL(image);
1816 if (dst.isEmpty()) {
1817 return;
1818 }
1819
1820 SkIRect bounds;
1821 Lattice latticePlusBounds = lattice;
1822 if (!latticePlusBounds.fBounds) {
1823 bounds = SkIRect::MakeWH(image->width(), image->height());
1824 latticePlusBounds.fBounds = &bounds;
1825 }
1826
1827 SkPaint latticePaint = clean_paint_for_lattice(paint);
1828 if (SkLatticeIter::Valid(image->width(), image->height(), latticePlusBounds)) {
1829 this->onDrawImageLattice2(image, latticePlusBounds, dst, filter, &latticePaint);
1830 } else {
1831 this->drawImageRect(image, SkRect::MakeIWH(image->width(), image->height()), dst,
1832 SkSamplingOptions(filter), &latticePaint, kStrict_SrcRectConstraint);
1833 }
1834 }
1835
1836 void SkCanvas::drawAtlas(const SkImage* atlas, SkSpan<const SkRSXform> xform,
1837 SkSpan<const SkRect> tex, SkSpan<const SkColor> colors, SkBlendMode mode,
1838 const SkSamplingOptions& sampling, const SkRect* cull,
1839 const SkPaint* paint) {
1840 TRACE_EVENT0("skia", TRACE_FUNC);
1841 RETURN_ON_NULL(atlas);
1842 size_t count = std::min(xform.size(), tex.size());
1843 if (!colors.empty()) {
1844 count = std::min(count, colors.size());
1845 }
1846 if (count == 0) {
1847 return;
1848 }
1849 this->onDrawAtlas2(atlas, xform.data(), tex.data(), colors.data(), count, mode, sampling,
1850 cull, paint);
1851 }
1852
1853 void SkCanvas::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
1854 TRACE_EVENT0("skia", TRACE_FUNC);
1855 if (key) {
1856 this->onDrawAnnotation(rect, key, value);
1857 }
1858 }
1859
1860 void SkCanvas::private_draw_shadow_rec(const SkPath& path, const SkDrawShadowRec& rec) {
1861 TRACE_EVENT0("skia", TRACE_FUNC);
1862 this->onDrawShadowRec(path, rec);
1863 }
1864
1865 void SkCanvas::onDrawShadowRec(const SkPath& path, const SkDrawShadowRec& rec) {
1866 // We don't test quickReject because the shadow outsets the path's bounds.
1867 // TODO(michaelludwig): Is it worth calling SkDrawShadowMetrics::GetLocalBounds here?
1868 if (!this->predrawNotify()) {
1869 return;
1870 }
1871 this->topDevice()->drawShadow(this, path, rec);
1872 }
1873
1874 void SkCanvas::experimental_DrawEdgeAAQuad(const SkRect& rect, const SkPoint clip[4],
1875 QuadAAFlags aaFlags, const SkColor4f& color,
1876 SkBlendMode mode) {
1877 TRACE_EVENT0("skia", TRACE_FUNC);
1878 // Make sure the rect is sorted before passing it along
1879 this->onDrawEdgeAAQuad(rect.makeSorted(), clip, aaFlags, color, mode);
1880 }
1881
1882 void SkCanvas::experimental_DrawEdgeAAImageSet(const ImageSetEntry imageSet[], int cnt,
1883 const SkPoint dstClips[],
1884 const SkMatrix preViewMatrices[],
1885 const SkSamplingOptions& sampling,
1886 const SkPaint* paint,
1887 SrcRectConstraint constraint) {
1888 TRACE_EVENT0("skia", TRACE_FUNC);
1889 // Route single, rectangular quads to drawImageRect() to take advantage of image filter
1890 // optimizations that avoid a layer.
1891 if (paint && (paint->getImageFilter() || paint->getMaskFilter()) && cnt == 1) {
1892 const auto& entry = imageSet[0];
1893 // If the preViewMatrix is skipped or a positive-scale + translate matrix, we can apply it
1894 // to the entry's dstRect w/o changing output behavior.
1895 const bool canMapDstRect = entry.fMatrixIndex < 0 ||
1896 (preViewMatrices[entry.fMatrixIndex].isScaleTranslate() &&
1897 preViewMatrices[entry.fMatrixIndex].getScaleX() > 0.f &&
1898 preViewMatrices[entry.fMatrixIndex].getScaleY() > 0.f);
1899 if (!entry.fHasClip && canMapDstRect) {
1900 SkRect dst = entry.fDstRect;
1901 if (entry.fMatrixIndex >= 0) {
1902 preViewMatrices[entry.fMatrixIndex].mapRect(&dst);
1903 }
1904 this->drawImageRect(entry.fImage.get(), entry.fSrcRect, dst,
1905 sampling, paint, constraint);
1906 return;
1907 } // Else the entry is doing more than can be represented by drawImageRect
1908 } // Else no filter, or many entries that should be filtered together
1909 this->onDrawEdgeAAImageSet2(imageSet, cnt, dstClips, preViewMatrices, sampling, paint,
1910 constraint);
1911 }
1912
1913 //////////////////////////////////////////////////////////////////////////////
1914 // These are the virtual drawing methods
1915 //////////////////////////////////////////////////////////////////////////////
1916
1917 void SkCanvas::onDiscard() {
1918 if (fSurfaceBase) {
1919 sk_ignore_unused_variable(fSurfaceBase->aboutToDraw(SkSurface::kDiscard_ContentChangeMode));
1920 }
1921 }
1922
1923 void SkCanvas::onDrawPaint(const SkPaint& paint) {
1924 this->internalDrawPaint(paint);
1925 }
1926
1927 void SkCanvas::internalDrawPaint(const SkPaint& paint) {
1928 // drawPaint does not call internalQuickReject() because computing its geometry is not free
1929 // (see getLocalClipBounds(), and the two conditions below are sufficient.
1930 if (this->nothingToDraw(paint) || this->isClipEmpty()) {
1931 return;
1932 }
1933
1934 auto layer = this->aboutToDraw(paint, nullptr, PredrawFlags::kCheckForOverwrite);
1935 if (layer) {
1936 this->topDevice()->drawPaint(layer->paint());
1937 }
1938 }
1939
1940 void SkCanvas::onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
1941 const SkPaint& paint) {
1942 if ((long)count <= 0 || this->nothingToDraw(paint)) {
1943 return;
1944 }
1945 SkASSERT(pts != nullptr);
1946
1947 // Enforce paint style matches implicit behavior of drawPoints
1948 SkPaint strokePaint = paint;
1949 strokePaint.setStyle(SkPaint::kStroke_Style);
1950
1951 SkRect boundsStorage;
1952 const SkRect* boundsPtr = nullptr;
1953
1954 /*
1955 * Computing the bounds can actually slow us down (since we check inside).
1956 * But if there is a filter, then it is useful to limit the size of
1957 * its offscreen, hence we only compute it in those cases.
1958 *
1959 * Note: it would be "correct" to never compute this, it is just considered
1960 * an optimization opportunity.
1961 */
1962 if (paint.getImageFilter() || paint.getMaskFilter()) {
1963 auto bounds = SkRect::Bounds({pts, count});
1964 if (!bounds) {
1965 return;
1966 }
1967 if (this->internalQuickReject(bounds.value(), strokePaint)) {
1968 return;
1969 }
1970 boundsStorage = bounds.value();
1971 boundsPtr = &boundsStorage;
1972 }
1973
1974 auto layer = this->aboutToDraw(strokePaint, boundsPtr);
1975 if (layer) {
1976 this->topDevice()->drawPoints(mode, {pts, count}, layer->paint());
1977 }
1978 }
1979
1980 const SkBlurMaskFilterImpl* SkCanvas::canAttemptBlurredRRectDraw(const SkPaint& paint) const {
1981 if (!this->topDevice()->useDrawCoverageMaskForMaskFilters()) {
1982 // Perform a regular draw in the legacy mask filter case.
1983 return nullptr;
1984 }
1985
1986 if (paint.getPathEffect()) {
1987 return nullptr;
1988 }
1989
1990 // TODO: Once stroke-and-fill goes away, we can check the paint's style directly.
1991 if (SkStrokeRec(paint).getStyle() != SkStrokeRec::kFill_Style) {
1992 return nullptr;
1993 }
1994
1995 const SkMaskFilterBase* maskFilter = as_MFB(paint.getMaskFilter());
1996 if (!maskFilter || maskFilter->type() != SkMaskFilterBase::Type::kBlur) {
1997 return nullptr;
1998 }
1999
2000 const SkBlurMaskFilterImpl* blurMaskFilter =
2001 static_cast<const SkBlurMaskFilterImpl*>(maskFilter);
2002 if (blurMaskFilter->blurStyle() != kNormal_SkBlurStyle) {
2003 return nullptr;
2004 }
2005
2006 if (!this->getTotalMatrix().isSimilarity()) {
2007 // TODO: If the CTM does more than just translation, rotation, and uniform scale, then the
2008 // results of analytic blurring will be different than mask filter blurring. Skip the
2009 // specialized path in this case.
2010 return nullptr;
2011 }
2012
2013 return blurMaskFilter;
2014 }
2015
2016 std::optional<AutoLayerForImageFilter> SkCanvas::attemptBlurredRRectDraw(
2017 const SkRRect& rrect,
2018 const SkBlurMaskFilterImpl* blurMaskFilter,
2019 const SkPaint& paint,
2020 SkEnumBitMask<PredrawFlags> flags) {
2021 SkASSERT(blurMaskFilter && blurMaskFilter == this->canAttemptBlurredRRectDraw(paint) &&
2022 !(flags & PredrawFlags::kSkipMaskFilterAutoLayer));
2023 const SkRect& bounds = rrect.getBounds();
2024
2025 auto layer = this->aboutToDraw(paint, &bounds, flags | PredrawFlags::kSkipMaskFilterAutoLayer);
2026 if (!layer) {
2027 // predrawNotify failed.
2028 return std::nullopt;
2029 }
2030
2031 const float deviceSigma = blurMaskFilter->computeXformedSigma(this->getTotalMatrix());
2032 if (this->topDevice()->drawBlurredRRect(rrect, layer->paint(), deviceSigma)) {
2033 // Analytic draw was successful.
2034 return std::nullopt;
2035 }
2036
2037 // Fall back on a regular draw, adding any mask filter layer we skipped earlier. We know the
2038 // paint has a mask filter here, otherwise we would have failed the can_attempt check above.
2039 layer->addMaskFilterLayer(&bounds);
2040 return layer;
2041 }
2042
2043 void SkCanvas::onDrawRect(const SkRect& r, const SkPaint& paint) {
2044 SkASSERT(r.isSorted());
2045 if (this->internalQuickReject(r, paint)) {
2046 return;
2047 }
2048
2049 std::optional<AutoLayerForImageFilter> layer;
2050 constexpr PredrawFlags kPredrawFlags = PredrawFlags::kCheckForOverwrite;
2051
2052 if (const SkBlurMaskFilterImpl* blurMaskFilter = this->canAttemptBlurredRRectDraw(paint)) {
2053 // Returns a layer if a blurred draw was unsuccessful.
2054 layer = this->attemptBlurredRRectDraw(
2055 SkRRect::MakeRect(r), blurMaskFilter, paint, kPredrawFlags);
2056 } else {
2057 layer = this->aboutToDraw(paint, &r, kPredrawFlags);
2058 }
2059
2060 if (layer) {
2061 this->topDevice()->drawRect(r, layer->paint());
2062 }
2063 }
2064
2065 void SkCanvas::onDrawRegion(const SkRegion& region, const SkPaint& paint) {
2066 const SkRect bounds = SkRect::Make(region.getBounds());
2067 if (this->internalQuickReject(bounds, paint)) {
2068 return;
2069 }
2070
2071 auto layer = this->aboutToDraw(paint, &bounds);
2072 if (layer) {
2073 this->topDevice()->drawRegion(region, layer->paint());
2074 }
2075 }
2076
2077 void SkCanvas::onDrawBehind(const SkPaint& paint) {
2078 SkDevice* dev = this->topDevice();
2079 if (!dev) {
2080 return;
2081 }
2082
2083 SkIRect bounds;
2084 SkDeque::Iter iter(fMCStack, SkDeque::Iter::kBack_IterStart);
2085 for (;;) {
2086 const MCRec* rec = (const MCRec*)iter.prev();
2087 if (!rec) {
2088 return; // no backimages, so nothing to draw
2089 }
2090 if (rec->fBackImage) {
2091 // drawBehind should only have been called when the saveBehind record is active;
2092 // if this fails, it means a real saveLayer was made w/o being restored first.
2093 SkASSERT(dev == rec->fDevice);
2094 bounds = SkIRect::MakeXYWH(rec->fBackImage->fLoc.fX, rec->fBackImage->fLoc.fY,
2095 rec->fBackImage->fImage->width(),
2096 rec->fBackImage->fImage->height());
2097 break;
2098 }
2099 }
2100
2101 // The backimage location (and thus bounds) were defined in the device's space, so mark it
2102 // as a clip. We use a clip instead of just drawing a rect in case the paint has an image
2103 // filter on it (which is applied before any auto-layer so the filter is clipped).
2104 dev->pushClipStack();
2105 {
2106 // We also have to temporarily whack the device matrix since clipRegion is affected by the
2107 // global-to-device matrix and clipRect is affected by the local-to-device.
2108 SkAutoDeviceTransformRestore adtr(dev, SkM44());
2109 dev->clipRect(SkRect::Make(bounds), SkClipOp::kIntersect, /* aa */ false);
2110 // ~adtr will reset the local-to-device matrix so that drawPaint() shades correctly.
2111 }
2112
2113 auto layer = this->aboutToDraw(paint);
2114 if (layer) {
2115 this->topDevice()->drawPaint(layer->paint());
2116 }
2117
2118 dev->popClipStack();
2119 }
2120
2121 void SkCanvas::onDrawOval(const SkRect& oval, const SkPaint& paint) {
2122 SkASSERT(oval.isSorted());
2123 if (this->internalQuickReject(oval, paint)) {
2124 return;
2125 }
2126
2127 std::optional<AutoLayerForImageFilter> layer;
2128
2129 if (const SkBlurMaskFilterImpl* blurMaskFilter = this->canAttemptBlurredRRectDraw(paint)) {
2130 // Returns a layer if a blurred draw was unsuccessful.
2131 layer = this->attemptBlurredRRectDraw(
2132 SkRRect::MakeOval(oval), blurMaskFilter, paint, PredrawFlags::kNone);
2133 } else {
2134 layer = this->aboutToDraw(paint, &oval);
2135 }
2136
2137 if (layer) {
2138 this->topDevice()->drawOval(oval, layer->paint());
2139 }
2140 }
2141
2142 void SkCanvas::onDrawArc(const SkRect& oval, SkScalar startAngle,
2143 SkScalar sweepAngle, bool useCenter,
2144 const SkPaint& paint) {
2145 SkASSERT(oval.isSorted());
2146 if (this->internalQuickReject(oval, paint)) {
2147 return;
2148 }
2149
2150 std::optional<AutoLayerForImageFilter> layer;
2151
2152 // Arcs with sweeps >= 360° are ovals. In this case, attempt a specialized blurred draw.
2153 if (const SkBlurMaskFilterImpl* blurMaskFilter = this->canAttemptBlurredRRectDraw(paint);
2154 blurMaskFilter && SkScalarAbs(sweepAngle) >= 360.f) {
2155 // Returns a layer if a blurred draw was unsuccessful.
2156 layer = this->attemptBlurredRRectDraw(
2157 SkRRect::MakeOval(oval), blurMaskFilter, paint, PredrawFlags::kNone);
2158 } else {
2159 layer = this->aboutToDraw(paint, &oval);
2160 }
2161
2162 if (layer) {
2163 this->topDevice()->drawArc(SkArc::Make(oval, startAngle, sweepAngle, useCenter),
2164 layer->paint());
2165 }
2166 }
2167
2168 void SkCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) {
2169 const SkRect& bounds = rrect.getBounds();
2170
2171 // Delegating to simpler draw operations
2172 if (rrect.isRect()) {
2173 // call the non-virtual version
2174 this->SkCanvas::drawRect(bounds, paint);
2175 return;
2176 } else if (rrect.isOval()) {
2177 // call the non-virtual version
2178 this->SkCanvas::drawOval(bounds, paint);
2179 return;
2180 }
2181
2182 if (this->internalQuickReject(bounds, paint)) {
2183 return;
2184 }
2185
2186 std::optional<AutoLayerForImageFilter> layer;
2187
2188 if (const SkBlurMaskFilterImpl* blurMaskFilter = this->canAttemptBlurredRRectDraw(paint)) {
2189 // Returns a layer if a blurred draw was unsuccessful.
2190 layer = this->attemptBlurredRRectDraw(rrect, blurMaskFilter, paint, PredrawFlags::kNone);
2191 } else {
2192 layer = this->aboutToDraw(paint, &bounds);
2193 }
2194
2195 if (layer) {
2196 this->topDevice()->drawRRect(rrect, layer->paint());
2197 }
2198 }
2199
2200 void SkCanvas::onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
2201 const SkRect& bounds = outer.getBounds();
2202 if (this->internalQuickReject(bounds, paint)) {
2203 return;
2204 }
2205
2206 auto layer = this->aboutToDraw(paint, &bounds);
2207 if (layer) {
2208 this->topDevice()->drawDRRect(outer, inner, layer->paint());
2209 }
2210 }
2211
2212 void SkCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {
2213 if (!path.isFinite()) {
2214 return;
2215 }
2216
2217 const SkRect& pathBounds = path.getBounds();
2218 if (!path.isInverseFillType() && this->internalQuickReject(pathBounds, paint)) {
2219 return;
2220 }
2221 if (path.isInverseFillType() && pathBounds.width() <= 0 && pathBounds.height() <= 0) {
2222 this->internalDrawPaint(paint);
2223 return;
2224 }
2225
2226 auto layer = this->aboutToDraw(paint, path.isInverseFillType() ? nullptr : &pathBounds);
2227 if (layer) {
2228 this->topDevice()->drawPath(path, layer->paint());
2229 }
2230 }
2231
2232 // Clean-up the paint to match the drawing semantics for drawImage et al. (skbug.com/40039059).
2233 static SkPaint clean_paint_for_drawImage(const SkPaint* paint) {
2234 SkPaint cleaned;
2235 if (paint) {
2236 cleaned = *paint;
2237 cleaned.setStyle(SkPaint::kFill_Style);
2238 cleaned.setPathEffect(nullptr);
2239 }
2240 return cleaned;
2241 }
2242
2243 // drawVertices fills triangles and ignores mask filter and path effect,
2244 // so canonicalize the paint before checking quick reject.
2245 static SkPaint clean_paint_for_drawVertices(SkPaint paint) {
2246 paint.setStyle(SkPaint::kFill_Style);
2247 paint.setMaskFilter(nullptr);
2248 paint.setPathEffect(nullptr);
2249 return paint;
2250 }
2251
2252 // TODO: Delete this since it is no longer used
2253 void SkCanvas::onDrawImage2(const SkImage* image, SkScalar x, SkScalar y,
2254 const SkSamplingOptions& sampling, const SkPaint* paint) {
2255 SkUNREACHABLE;
2256 }
2257
2258 static SkSamplingOptions clean_sampling_for_constraint(
2259 const SkSamplingOptions& sampling,
2260 SkCanvas::SrcRectConstraint constraint) {
2261 if (constraint == SkCanvas::kStrict_SrcRectConstraint) {
2262 if (sampling.mipmap != SkMipmapMode::kNone) {
2263 return SkSamplingOptions(sampling.filter);
2264 }
2265 if (sampling.isAniso()) {
2266 return SkSamplingOptions(SkFilterMode::kLinear);
2267 }
2268 }
2269 return sampling;
2270 }
2271
2272 void SkCanvas::onDrawImageRect2(const SkImage* image, const SkRect& src, const SkRect& dst,
2273 const SkSamplingOptions& sampling, const SkPaint* paint,
2274 SrcRectConstraint constraint) {
2275 SkPaint realPaint = clean_paint_for_drawImage(paint);
2276 SkSamplingOptions realSampling = clean_sampling_for_constraint(sampling, constraint);
2277
2278 if (this->internalQuickReject(dst, realPaint)) {
2279 return;
2280 }
2281
2282 if (this->topDevice()->shouldDrawAsTiledImageRect()) {
2283 if (this->topDevice()->drawAsTiledImageRect(
2284 this, image, &src, dst, realSampling, realPaint, constraint)) {
2285 return;
2286 }
2287 }
2288
2289 // drawImageRect()'s behavior is modified by the presence of an image filter, a mask filter, a
2290 // color filter, the paint's alpha, the paint's blender, and--when it's an alpha-only image--
2291 // the paint's color or shader. When there's an image filter, the paint's blender is applied to
2292 // the result of the image filter function, but every other aspect would influence the source
2293 // image that's then rendered with src-over blending into a transparent temporary layer.
2294 //
2295 // However, skif::FilterResult can apply the paint alpha and any color filter often without
2296 // requiring a layer, and src-over blending onto a transparent dst is a no-op, so we can use the
2297 // input image directly as the source for filtering. When the image is alpha-only and must be
2298 // colorized, or when a mask filter would change the coverage we skip this optimization for
2299 // simplicity since *somehow* embedding colorization or mask blurring into the filter graph
2300 // would likely be equivalent to using the existing AutoLayerForImageFilter functionality.
2301 if (realPaint.getImageFilter() && !image->isAlphaOnly() && !realPaint.getMaskFilter()) {
2302 SkDevice* device = this->topDevice();
2303
2304 skif::ParameterSpace<SkRect> imageBounds{dst};
2305 skif::DeviceSpace<SkIRect> outputBounds{device->devClipBounds()};
2306 FilterToSpan filterAsSpan(realPaint.getImageFilter());
2307 auto mappingAndBounds = get_layer_mapping_and_bounds(filterAsSpan,
2308 device->localToDevice44(),
2309 outputBounds,
2310 imageBounds);
2311 if (!mappingAndBounds) {
2312 return;
2313 }
2314 if (!this->predrawNotify()) {
2315 return;
2316 }
2317
2318 // Start out with an empty source image, to be replaced with the converted 'image', and a
2319 // desired output equal to the calculated initial source layer bounds, which accounts for
2320 // how the image filters will access 'image' (possibly different than just 'outputBounds').
2321 auto backend = device->createImageFilteringBackend(
2322 device->surfaceProps(),
2323 image_filter_color_type(device->imageInfo().colorInfo()));
2324 auto [mapping, srcBounds] = *mappingAndBounds;
2325 skif::Stats stats;
2326 skif::Context ctx{std::move(backend),
2327 mapping,
2328 srcBounds,
2329 skif::FilterResult{},
2330 device->imageInfo().colorSpace(),
2331 &stats};
2332
2333 auto source = skif::FilterResult::MakeFromImage(
2334 ctx, sk_ref_sp(image), src, imageBounds, sampling);
2335 // Apply effects that are normally processed on the draw *before* any layer/image filter.
2336 source = apply_alpha_and_colorfilter(ctx, source, realPaint);
2337
2338 // Evaluate the image filter, with a context pointing to the source created directly from
2339 // 'image' (which will not require intermediate renderpasses when 'src' is integer aligned).
2340 // and a desired output matching the device clip bounds.
2341 ctx = ctx.withNewDesiredOutput(mapping.deviceToLayer(outputBounds))
2342 .withNewSource(source);
2343 auto result = as_IFB(realPaint.getImageFilter())->filterImage(ctx);
2344 result.draw(ctx, device, realPaint.getBlender());
2345 stats.reportStats();
2346 return;
2347 }
2348
2349 if (realPaint.getMaskFilter() && this->topDevice()->useDrawCoverageMaskForMaskFilters()) {
2350 // Route mask-filtered drawImages to drawRect() to use the auto-layer for mask filters,
2351 // which require all shading to be encoded in the paint.
2352 auto [drawDstRect, shader] = SkImageShader::MakeForDrawRect(
2353 image, realPaint, sampling, src, dst, constraint == kStrict_SrcRectConstraint);
2354 if (drawDstRect.isEmpty() || !shader) {
2355 return;
2356 }
2357 realPaint.setShader(std::move(shader));
2358 this->drawRect(drawDstRect, realPaint);
2359 return;
2360 }
2361
2362 auto layer = this->aboutToDraw(realPaint, &dst,
2363 PredrawFlags::kCheckForOverwrite |
2364 (image->isOpaque() ? PredrawFlags::kOpaqueShaderOverride
2365 : PredrawFlags::kNonOpaqueShaderOverride));
2366 if (layer) {
2367 this->topDevice()->drawImageRect(image, &src, dst, realSampling, layer->paint(),
2368 constraint);
2369 }
2370 }
2371
2372 void SkCanvas::onDrawImageLattice2(const SkImage* image, const Lattice& lattice, const SkRect& dst,
2373 SkFilterMode filter, const SkPaint* paint) {
2374 SkPaint realPaint = clean_paint_for_drawImage(paint);
2375
2376 if (this->internalQuickReject(dst, realPaint)) {
2377 return;
2378 }
2379
2380 auto layer = this->aboutToDraw(realPaint, &dst);
2381 if (layer) {
2382 this->topDevice()->drawImageLattice(image, lattice, dst, filter, layer->paint());
2383 }
2384 }
2385
2386 void SkCanvas::drawImage(const SkImage* image, SkScalar x, SkScalar y,
2387 const SkSamplingOptions& sampling, const SkPaint* paint) {
2388 TRACE_EVENT0("skia", TRACE_FUNC);
2389 RETURN_ON_NULL(image);
2390
2391 this->drawImageRect(image,
2392 /*src=*/SkRect::MakeWH(image->width(), image->height()),
2393 /*dst=*/SkRect::MakeXYWH(x, y, image->width(), image->height()),
2394 sampling,
2395 paint,
2396 kFast_SrcRectConstraint);
2397 }
2398
2399 void SkCanvas::drawImageRect(const SkImage* image, const SkRect& src, const SkRect& dst,
2400 const SkSamplingOptions& sampling, const SkPaint* paint,
2401 SrcRectConstraint constraint) {
2402 RETURN_ON_NULL(image);
2403 if (!fillable(dst) || !fillable(src)) {
2404 return;
2405 }
2406 this->onDrawImageRect2(image, src, dst, sampling, paint, constraint);
2407 }
2408
2409 void SkCanvas::drawImageRect(const SkImage* image, const SkRect& dst,
2410 const SkSamplingOptions& sampling, const SkPaint* paint) {
2411 RETURN_ON_NULL(image);
2412 this->drawImageRect(image, SkRect::MakeIWH(image->width(), image->height()), dst, sampling,
2413 paint, kFast_SrcRectConstraint);
2414 }
2415
2416 void SkCanvas::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
2417 const SkPaint& paint) {
2418 auto glyphRunList = fScratchGlyphRunBuilder->blobToGlyphRunList(*blob, {x, y});
2419 this->onDrawGlyphRunList(glyphRunList, paint);
2420 }
2421
2422 void SkCanvas::onDrawGlyphRunList(const sktext::GlyphRunList& glyphRunList, const SkPaint& paint) {
2423 SkRect bounds = glyphRunList.sourceBoundsWithOrigin();
2424 if (this->internalQuickReject(bounds, paint)) {
2425 return;
2426 }
2427
2428 // Text attempts to apply any SkMaskFilter internally and save the blurred masks in the
2429 // strike cache; if a glyph must be drawn as a path or drawable, SkDevice routes back to
2430 // this SkCanvas to retry, which will go through a function that does *not* skip the mask
2431 // filter layer.
2432 auto layer = this->aboutToDraw(paint, &bounds, PredrawFlags::kSkipMaskFilterAutoLayer);
2433 if (layer) {
2434 this->topDevice()->drawGlyphRunList(this, glyphRunList, layer->paint());
2435 }
2436 }
2437
2438 sk_sp<Slug> SkCanvas::convertBlobToSlug(
2439 const SkTextBlob& blob, SkPoint origin, const SkPaint& paint) {
2440 TRACE_EVENT0("skia", TRACE_FUNC);
2441 auto glyphRunList = fScratchGlyphRunBuilder->blobToGlyphRunList(blob, origin);
2442 return this->onConvertGlyphRunListToSlug(glyphRunList, paint);
2443 }
2444
2445 sk_sp<Slug> SkCanvas::onConvertGlyphRunListToSlug(const sktext::GlyphRunList& glyphRunList,
2446 const SkPaint& paint) {
2447 SkRect bounds = glyphRunList.sourceBoundsWithOrigin();
2448 if (bounds.isEmpty() || !bounds.isFinite() || this->nothingToDraw(paint)) {
2449 return nullptr;
2450 }
2451 // See comment in onDrawGlyphRunList()
2452 auto layer = this->aboutToDraw(paint, &bounds, PredrawFlags::kSkipMaskFilterAutoLayer);
2453 if (layer) {
2454 return this->topDevice()->convertGlyphRunListToSlug(glyphRunList, layer->paint());
2455 }
2456 return nullptr;
2457 }
2458
2459 void SkCanvas::drawSlug(const Slug* slug, const SkPaint& paint) {
2460 TRACE_EVENT0("skia", TRACE_FUNC);
2461 if (slug) {
2462 this->onDrawSlug(slug, paint);
2463 }
2464 }
2465
2466 void SkCanvas::onDrawSlug(const Slug* slug, const SkPaint& paint) {
2467 SkRect bounds = slug->sourceBoundsWithOrigin();
2468 if (this->internalQuickReject(bounds, paint)) {
2469 return;
2470 }
2471 // See comment in onDrawGlyphRunList()
2472 auto layer = this->aboutToDraw(paint, &bounds, PredrawFlags::kSkipMaskFilterAutoLayer);
2473 if (layer) {
2474 this->topDevice()->drawSlug(this, slug, layer->paint());
2475 }
2476 }
2477
2478 // These call the (virtual) onDraw... method
2479 void SkCanvas::drawSimpleText(const void* text, size_t byteLength, SkTextEncoding encoding,
2480 SkScalar x, SkScalar y, const SkFont& font, const SkPaint& paint) {
2481 TRACE_EVENT0("skia", TRACE_FUNC);
2482 if (byteLength) {
2483 sk_msan_assert_initialized(text, SkTAddOffset<const void>(text, byteLength));
2484 const sktext::GlyphRunList& glyphRunList =
2485 fScratchGlyphRunBuilder->textToGlyphRunList(
2486 font, paint, text, byteLength, {x, y}, encoding);
2487 if (!glyphRunList.empty()) {
2488 this->onDrawGlyphRunList(glyphRunList, paint);
2489 }
2490 }
2491 }
2492
2493 void SkCanvas::drawGlyphs(SkSpan<const SkGlyphID> glyphs, SkSpan<const SkPoint> positions,
2494 SkSpan<const uint32_t> clusters, SkSpan<const char> utf8text,
2495 SkPoint origin, const SkFont& font, const SkPaint& paint) {
2496 if (glyphs.empty()) { return; }
2497
2498 sktext::GlyphRun glyphRun {
2499 font,
2500 positions,
2501 glyphs,
2502 utf8text,
2503 clusters,
2504 SkSpan<SkVector>()
2505 };
2506
2507 sktext::GlyphRunList glyphRunList = fScratchGlyphRunBuilder->makeGlyphRunList(
2508 glyphRun, paint, origin);
2509 this->onDrawGlyphRunList(glyphRunList, paint);
2510 }
2511
2512 void SkCanvas::drawGlyphs(SkSpan<const SkGlyphID> glyphs, SkSpan<const SkPoint> positions,
2513 SkPoint origin, const SkFont& font, const SkPaint& paint) {
2514 if (glyphs.empty()) { return; }
2515
2516 sktext::GlyphRun glyphRun {
2517 font,
2518 positions,
2519 glyphs,
2520 SkSpan<const char>(),
2521 SkSpan<const uint32_t>(),
2522 SkSpan<SkVector>()
2523 };
2524
2525 sktext::GlyphRunList glyphRunList = fScratchGlyphRunBuilder->makeGlyphRunList(
2526 glyphRun, paint, origin);
2527 this->onDrawGlyphRunList(glyphRunList, paint);
2528 }
2529
2530 void SkCanvas::drawGlyphsRSXform(SkSpan<const SkGlyphID> glyphs, SkSpan<const SkRSXform> xforms,
2531 SkPoint origin, const SkFont& font, const SkPaint& paint) {
2532 if (glyphs.empty()) { return; }
2533
2534 auto [positions, rotateScales] =
2535 fScratchGlyphRunBuilder->convertRSXForm(xforms);
2536
2537 sktext::GlyphRun glyphRun {
2538 font,
2539 positions,
2540 glyphs,
2541 SkSpan<const char>(),
2542 SkSpan<const uint32_t>(),
2543 rotateScales
2544 };
2545 sktext::GlyphRunList glyphRunList = fScratchGlyphRunBuilder->makeGlyphRunList(
2546 glyphRun, paint, origin);
2547 this->onDrawGlyphRunList(glyphRunList, paint);
2548 }
2549
2550 void SkCanvas::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
2551 const SkPaint& paint) {
2552 TRACE_EVENT0("skia", TRACE_FUNC);
2553 RETURN_ON_NULL(blob);
2554 RETURN_ON_FALSE(blob->bounds().makeOffset(x, y).isFinite());
2555
2556 // Overflow if more than 2^21 glyphs stopping a buffer overflow latter in the stack.
2557 // See chromium:1080481
2558 // TODO: can consider unrolling a few at a time if this limit becomes a problem.
2559 int totalGlyphCount = 0;
2560 constexpr int kMaxGlyphCount = 1 << 21;
2561 SkTextBlob::Iter i(*blob);
2562 SkTextBlob::Iter::Run r;
2563 while (i.next(&r)) {
2564 int glyphsLeft = kMaxGlyphCount - totalGlyphCount;
2565 RETURN_ON_FALSE(r.fGlyphCount <= glyphsLeft);
2566 totalGlyphCount += r.fGlyphCount;
2567 }
2568
2569 this->onDrawTextBlob(blob, x, y, paint);
2570 }
2571
2572 void SkCanvas::onDrawVerticesObject(const SkVertices* vertices, SkBlendMode bmode,
2573 const SkPaint& paint) {
2574 SkPaint simplePaint = clean_paint_for_drawVertices(paint);
2575
2576 const SkRect& bounds = vertices->bounds();
2577 if (this->internalQuickReject(bounds, simplePaint)) {
2578 return;
2579 }
2580
2581 auto layer = this->aboutToDraw(simplePaint, &bounds);
2582 if (layer) {
2583 this->topDevice()->drawVertices(vertices, SkBlender::Mode(bmode), layer->paint());
2584 }
2585 }
2586
2587 void SkCanvas::onDrawMesh(const SkMesh& mesh, sk_sp<SkBlender> blender, const SkPaint& paint) {
2588 SkPaint simplePaint = clean_paint_for_drawVertices(paint);
2589 auto layer = this->aboutToDraw(simplePaint, nullptr);
2590 if (layer) {
2591 this->topDevice()->drawMesh(mesh, std::move(blender), paint);
2592 }
2593 }
2594
2595 void SkCanvas::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
2596 const SkPoint texCoords[4], SkBlendMode bmode,
2597 const SkPaint& paint) {
2598 TRACE_EVENT0("skia", TRACE_FUNC);
2599 if (nullptr == cubics) {
2600 return;
2601 }
2602
2603 this->onDrawPatch(cubics, colors, texCoords, bmode, paint);
2604 }
2605
2606 void SkCanvas::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
2607 const SkPoint texCoords[4], SkBlendMode bmode,
2608 const SkPaint& paint) {
2609 auto bounds = SkRect::Bounds({cubics, (size_t)SkPatchUtils::kNumCtrlPts});
2610 if (!bounds) {
2611 return; // we don't draw if the bounds are not finite
2612 }
2613
2614 // drawPatch has the same behavior restrictions as drawVertices
2615 SkPaint simplePaint = clean_paint_for_drawVertices(paint);
2616
2617 // Since a patch is always within the convex hull of the control points, we discard it when its
2618 // bounding rectangle is completely outside the current clip.
2619 if (this->internalQuickReject(bounds.value(), simplePaint)) {
2620 return;
2621 }
2622
2623 auto r = bounds.value();
2624 auto layer = this->aboutToDraw(simplePaint, &r);
2625 if (layer) {
2626 this->topDevice()->drawPatch(cubics, colors, texCoords, SkBlender::Mode(bmode),
2627 layer->paint());
2628 }
2629 }
2630
2631 void SkCanvas::drawDrawable(SkDrawable* dr, SkScalar x, SkScalar y) {
2632 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
2633 TRACE_EVENT0("skia", TRACE_FUNC);
2634 #endif
2635 RETURN_ON_NULL(dr);
2636 if (x || y) {
2637 SkMatrix matrix = SkMatrix::Translate(x, y);
2638 this->onDrawDrawable(dr, &matrix);
2639 } else {
2640 this->onDrawDrawable(dr, nullptr);
2641 }
2642 }
2643
2644 void SkCanvas::drawDrawable(SkDrawable* dr, const SkMatrix* matrix) {
2645 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
2646 TRACE_EVENT0("skia", TRACE_FUNC);
2647 #endif
2648 RETURN_ON_NULL(dr);
2649 if (matrix && matrix->isIdentity()) {
2650 matrix = nullptr;
2651 }
2652 this->onDrawDrawable(dr, matrix);
2653 }
2654
2655 void SkCanvas::onDrawDrawable(SkDrawable* dr, const SkMatrix* matrix) {
2656 // drawable bounds are no longer reliable (e.g. android displaylist)
2657 // so don't use them for quick-reject
2658 if (this->predrawNotify()) {
2659 this->topDevice()->drawDrawable(this, dr, matrix);
2660 }
2661 }
2662
2663 void SkCanvas::onDrawAtlas2(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
2664 const SkColor colors[], int count, SkBlendMode bmode,
2665 const SkSamplingOptions& sampling, const SkRect* cull,
2666 const SkPaint* paint) {
2667 // drawAtlas is a combination of drawVertices and drawImage...
2668 SkPaint realPaint = clean_paint_for_drawVertices(clean_paint_for_drawImage(paint));
2669 realPaint.setShader(atlas->makeShader(sampling));
2670
2671 if (cull && this->internalQuickReject(*cull, realPaint)) {
2672 return;
2673 }
2674
2675 // drawAtlas should not have mask filters on its paint, so we don't need to worry about
2676 // converting its "drawImage" behavior into the paint to work with the auto-mask-filter system.
2677 SkASSERT(!realPaint.getMaskFilter());
2678 auto layer = this->aboutToDraw(realPaint);
2679 if (layer) {
2680 size_t N = SkToSizeT(count);
2681 this->topDevice()->drawAtlas({xform, N}, {tex, N}, {colors, colors ? N : 0},
2682 SkBlender::Mode(bmode), layer->paint());
2683 }
2684 }
2685
2686 void SkCanvas::onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
2687 SkASSERT(key);
2688
2689 if (this->predrawNotify()) {
2690 this->topDevice()->drawAnnotation(rect, key, value);
2691 }
2692 }
2693
2694 void SkCanvas::onDrawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], QuadAAFlags edgeAA,
2695 const SkColor4f& color, SkBlendMode mode) {
2696 SkASSERT(r.isSorted());
2697
2698 SkPaint paint{color};
2699 paint.setBlendMode(mode);
2700 if (this->internalQuickReject(r, paint)) {
2701 return;
2702 }
2703
2704 if (this->predrawNotify()) {
2705 this->topDevice()->drawEdgeAAQuad(r, clip, edgeAA, color, mode);
2706 }
2707 }
2708
2709 void SkCanvas::onDrawEdgeAAImageSet2(const ImageSetEntry imageSet[], int count,
2710 const SkPoint dstClips[], const SkMatrix preViewMatrices[],
2711 const SkSamplingOptions& sampling, const SkPaint* paint,
2712 SrcRectConstraint constraint) {
2713 if (count <= 0) {
2714 // Nothing to draw
2715 return;
2716 }
2717
2718 SkPaint realPaint = clean_paint_for_drawImage(paint);
2719 SkSamplingOptions realSampling = clean_sampling_for_constraint(sampling, constraint);
2720
2721 // We could calculate the set's dstRect union to always check quickReject(), but we can't reject
2722 // individual entries and Chromium's occlusion culling already makes it likely that at least one
2723 // entry will be visible. So, we only calculate the draw bounds when it's trivial (count == 1),
2724 // or we need it for the autolooper (since it greatly improves image filter perf).
2725 bool needsAutoLayer = SkToBool(realPaint.getImageFilter() || realPaint.getMaskFilter());
2726 bool setBoundsValid = count == 1 || needsAutoLayer;
2727 SkRect setBounds = imageSet[0].fDstRect;
2728 if (imageSet[0].fMatrixIndex >= 0) {
2729 // Account for the per-entry transform that is applied prior to the CTM when drawing
2730 preViewMatrices[imageSet[0].fMatrixIndex].mapRect(&setBounds);
2731 }
2732 if (needsAutoLayer) {
2733 for (int i = 1; i < count; ++i) {
2734 SkRect entryBounds = imageSet[i].fDstRect;
2735 if (imageSet[i].fMatrixIndex >= 0) {
2736 preViewMatrices[imageSet[i].fMatrixIndex].mapRect(&entryBounds);
2737 }
2738 setBounds.joinPossiblyEmptyRect(entryBounds);
2739 }
2740 }
2741
2742 // If we happen to have the draw bounds, though, might as well check quickReject().
2743 if (setBoundsValid && this->internalQuickReject(setBounds, realPaint)) {
2744 return;
2745 }
2746
2747 if (realPaint.getMaskFilter() && this->topDevice()->useDrawCoverageMaskForMaskFilters()) {
2748 // Route mask-filtered drawEdgeAAImageSets to drawEdgeAAQuad() or drawImageRect()
2749 // to use the auto-layer for mask filters, which require all shading to be encoded in
2750 // the paint.
2751 int dstClipIndex = 0;
2752 for (int i = 0; i < count; ++i) {
2753 SkPaint imagePaint = realPaint;
2754 auto [drawDstRect, shader] =
2755 SkImageShader::MakeForDrawRect(imageSet[i].fImage.get(),
2756 imagePaint,
2757 sampling,
2758 imageSet[i].fSrcRect,
2759 imageSet[i].fDstRect,
2760 constraint == kStrict_SrcRectConstraint);
2761 if (drawDstRect.isEmpty() || !shader) {
2762 return;
2763 }
2764 imagePaint.setShader(std::move(shader));
2765 auto layer = this->aboutToDraw(imagePaint, &drawDstRect);
2766 if (layer) {
2767 // Since we can't call mapRect to apply any preview matrix and drawEdgeAAQuad
2768 // doesn't take an optional matrix, we can modify the local-to-device matrix
2769 // of the layers top device.
2770 if (imageSet[i].fMatrixIndex >= 0) {
2771 this->topDevice()->setLocalToDevice(
2772 this->topDevice()->localToDevice44() *
2773 SkM44(preViewMatrices[imageSet[i].fMatrixIndex]));
2774 }
2775
2776 // Call drawEdgeAAImageSet on each image one at a time, to correctly
2777 // paint the image.
2778 this->topDevice()->drawEdgeAAQuad(drawDstRect,
2779 imageSet[i].fHasClip ? dstClips + dstClipIndex
2780 : nullptr,
2781 (QuadAAFlags)imageSet[i].fAAFlags,
2782 layer->paint().getColor4f(),
2783 SkBlendMode::kSrcOver);
2784 }
2785 dstClipIndex += 4 * imageSet[i].fHasClip;
2786 }
2787 return;
2788 }
2789
2790 auto layer = this->aboutToDraw(realPaint, setBoundsValid ? &setBounds : nullptr);
2791 if (layer) {
2792 this->topDevice()->drawEdgeAAImageSet(imageSet, count, dstClips, preViewMatrices,
2793 realSampling, layer->paint(), constraint);
2794 }
2795 }
2796
2797 //////////////////////////////////////////////////////////////////////////////
2798 // These methods are NOT virtual, and therefore must call back into virtual
2799 // methods, rather than actually drawing themselves.
2800 //////////////////////////////////////////////////////////////////////////////
2801
2802 void SkCanvas::drawColor(const SkColor4f& c, SkBlendMode mode) {
2803 SkPaint paint;
2804 paint.setColor(c);
2805 paint.setBlendMode(mode);
2806 this->drawPaint(paint);
2807 }
2808
2809 void SkCanvas::drawPoint(SkScalar x, SkScalar y, const SkPaint& paint) {
2810 const SkPoint pt[1] = {{ x, y }};
2811 this->drawPoints(kPoints_PointMode, pt, paint);
2812 }
2813
2814 void SkCanvas::drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1, const SkPaint& paint) {
2815 SkPoint pts[2];
2816 pts[0].set(x0, y0);
2817 pts[1].set(x1, y1);
2818 this->drawPoints(kLines_PointMode, pts, paint);
2819 }
2820
2821 void SkCanvas::drawCircle(SkScalar cx, SkScalar cy, SkScalar radius, const SkPaint& paint) {
2822 if (radius < 0) {
2823 radius = 0;
2824 }
2825
2826 SkRect r;
2827 r.setLTRB(cx - radius, cy - radius, cx + radius, cy + radius);
2828 this->drawOval(r, paint);
2829 }
2830
2831 void SkCanvas::drawRoundRect(const SkRect& r, SkScalar rx, SkScalar ry,
2832 const SkPaint& paint) {
2833 if (rx > 0 && ry > 0) {
2834 SkRRect rrect;
2835 rrect.setRectXY(r, rx, ry);
2836 this->drawRRect(rrect, paint);
2837 } else {
2838 this->drawRect(r, paint);
2839 }
2840 }
2841
2842 void SkCanvas::drawArc(const SkRect& oval, SkScalar startAngle,
2843 SkScalar sweepAngle, bool useCenter,
2844 const SkPaint& paint) {
2845 TRACE_EVENT0("skia", TRACE_FUNC);
2846 if (oval.isEmpty() || !sweepAngle) {
2847 return;
2848 }
2849 this->onDrawArc(oval, startAngle, sweepAngle, useCenter, paint);
2850 }
2851
2852 ///////////////////////////////////////////////////////////////////////////////
2853 #ifdef SK_DISABLE_SKPICTURE
2854 void SkCanvas::drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {}
2855
2856
2857 void SkCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
2858 const SkPaint* paint) {}
2859 #else
2860
2861 void SkCanvas::drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {
2862 TRACE_EVENT0("skia", TRACE_FUNC);
2863 RETURN_ON_NULL(picture);
2864
2865 if (matrix && matrix->isIdentity()) {
2866 matrix = nullptr;
2867 }
2868 if (picture->approximateOpCount() <= kMaxPictureOpsToUnrollInsteadOfRef) {
2869 SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
2870 picture->playback(this);
2871 } else {
2872 this->onDrawPicture(picture, matrix, paint);
2873 }
2874 }
2875
2876 void SkCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
2877 const SkPaint* paint) {
2878 if (this->internalQuickReject(picture->cullRect(), paint ? *paint : SkPaint{}, matrix)) {
2879 return;
2880 }
2881
2882 SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
2883 picture->playback(this);
2884 }
2885 #endif
2886
2887 ///////////////////////////////////////////////////////////////////////////////
2888
2889 SkCanvas::ImageSetEntry::ImageSetEntry() = default;
2890 SkCanvas::ImageSetEntry::~ImageSetEntry() = default;
2891 SkCanvas::ImageSetEntry::ImageSetEntry(const ImageSetEntry&) = default;
2892 SkCanvas::ImageSetEntry& SkCanvas::ImageSetEntry::operator=(const ImageSetEntry&) = default;
2893
2894 SkCanvas::ImageSetEntry::ImageSetEntry(sk_sp<const SkImage> image, const SkRect& srcRect,
2895 const SkRect& dstRect, int matrixIndex, float alpha,
2896 unsigned aaFlags, bool hasClip)
2897 : fImage(std::move(image))
2898 , fSrcRect(srcRect)
2899 , fDstRect(dstRect)
2900 , fMatrixIndex(matrixIndex)
2901 , fAlpha(alpha)
2902 , fAAFlags(aaFlags)
2903 , fHasClip(hasClip) {}
2904
2905 SkCanvas::ImageSetEntry::ImageSetEntry(sk_sp<const SkImage> image, const SkRect& srcRect,
2906 const SkRect& dstRect, float alpha, unsigned aaFlags)
2907 : fImage(std::move(image))
2908 , fSrcRect(srcRect)
2909 , fDstRect(dstRect)
2910 , fAlpha(alpha)
2911 , fAAFlags(aaFlags) {}
2912
2913 ///////////////////////////////////////////////////////////////////////////////
2914
2915 std::unique_ptr<SkCanvas> SkCanvas::MakeRasterDirect(const SkImageInfo& info, void* pixels,
2916 size_t rowBytes, const SkSurfaceProps* props) {
2917 if (!SkSurfaceValidateRasterInfo(info, rowBytes)) {
2918 return nullptr;
2919 }
2920
2921 SkBitmap bitmap;
2922 if (!bitmap.installPixels(info, pixels, rowBytes)) {
2923 return nullptr;
2924 }
2925
2926 return props ?
2927 std::make_unique<SkCanvas>(bitmap, *props) :
2928 std::make_unique<SkCanvas>(bitmap);
2929 }
2930
2931 ///////////////////////////////////////////////////////////////////////////////
2932
2933 SkNoDrawCanvas::SkNoDrawCanvas(int width, int height)
2934 : INHERITED(SkIRect::MakeWH(width, height)) {}
2935
2936 SkNoDrawCanvas::SkNoDrawCanvas(const SkIRect& bounds)
2937 : INHERITED(bounds) {}
2938
2939 SkCanvas::SaveLayerStrategy SkNoDrawCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {
2940 (void)this->INHERITED::getSaveLayerStrategy(rec);
2941 return kNoLayer_SaveLayerStrategy;
2942 }
2943
2944 bool SkNoDrawCanvas::onDoSaveBehind(const SkRect*) {
2945 return false;
2946 }
2947
2948 ///////////////////////////////////////////////////////////////////////////////
2949
2950 static_assert((int)SkRegion::kDifference_Op == (int)SkClipOp::kDifference, "");
2951 static_assert((int)SkRegion::kIntersect_Op == (int)SkClipOp::kIntersect, "");
2952
2953 ///////////////////////////////////////////////////////////////////////////////////////////////////
2954
2955 SkRasterHandleAllocator::Handle SkCanvas::accessTopRasterHandle() const {
2956 const SkDevice* dev = this->topDevice();
2957 if (fAllocator) {
2958 SkRasterHandleAllocator::Handle handle = dev->getRasterHandle();
2959 SkIRect clip = dev->devClipBounds();
2960 if (!clip.intersect({0, 0, dev->width(), dev->height()})) {
2961 clip.setEmpty();
2962 }
2963
2964 fAllocator->updateHandle(handle, dev->localToDevice(), clip);
2965 return handle;
2966 }
2967 return nullptr;
2968 }
2969
2970 static bool install(SkBitmap* bm, const SkImageInfo& info,
2971 const SkRasterHandleAllocator::Rec& rec) {
2972 return bm->installPixels(info, rec.fPixels, rec.fRowBytes, rec.fReleaseProc, rec.fReleaseCtx);
2973 }
2974
2975 SkRasterHandleAllocator::Handle SkRasterHandleAllocator::allocBitmap(const SkImageInfo& info,
2976 SkBitmap* bm) {
2977 SkRasterHandleAllocator::Rec rec;
2978 if (!this->allocHandle(info, &rec) || !install(bm, info, rec)) {
2979 return nullptr;
2980 }
2981 return rec.fHandle;
2982 }
2983
2984 std::unique_ptr<SkCanvas>
2985 SkRasterHandleAllocator::MakeCanvas(std::unique_ptr<SkRasterHandleAllocator> alloc,
2986 const SkImageInfo& info, const Rec* rec,
2987 const SkSurfaceProps* props) {
2988 if (!alloc || !SkSurfaceValidateRasterInfo(info, rec ? rec->fRowBytes : kIgnoreRowBytesValue)) {
2989 return nullptr;
2990 }
2991
2992 SkBitmap bm;
2993 Handle hndl;
2994
2995 if (rec) {
2996 hndl = install(&bm, info, *rec) ? rec->fHandle : nullptr;
2997 } else {
2998 hndl = alloc->allocBitmap(info, &bm);
2999 }
3000 return hndl ? std::unique_ptr<SkCanvas>(new SkCanvas(bm, std::move(alloc), hndl, props))
3001 : nullptr;
3002 }