Bug 1885565 - Part 1: Add mozac_ic_avatar_circle_24 to ui-icons r=android-reviewers...
[gecko.git] / image / ClippedImage.cpp
blobcad74ebdf8ad84ab359ae883182fd7894998a409
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "ClippedImage.h"
8 #include <algorithm>
9 #include <cmath>
10 #include <new> // Workaround for bug in VS10; see bug 981264.
11 #include <utility>
13 #include "ImageRegion.h"
14 #include "Orientation.h"
15 #include "gfxContext.h"
16 #include "gfxDrawable.h"
17 #include "gfxPlatform.h"
18 #include "gfxUtils.h"
19 #include "mozilla/RefPtr.h"
20 #include "mozilla/SVGImageContext.h"
22 #include "mozilla/gfx/2D.h"
24 namespace mozilla {
26 using namespace gfx;
27 using std::max;
29 namespace image {
31 class ClippedImageCachedSurface {
32 public:
33 ClippedImageCachedSurface(already_AddRefed<SourceSurface> aSurface,
34 const nsIntSize& aSize,
35 const SVGImageContext& aSVGContext, float aFrame,
36 uint32_t aFlags, ImgDrawResult aDrawResult)
37 : mSurface(aSurface),
38 mSize(aSize),
39 mSVGContext(aSVGContext),
40 mFrame(aFrame),
41 mFlags(aFlags),
42 mDrawResult(aDrawResult) {
43 MOZ_ASSERT(mSurface, "Must have a valid surface");
46 bool Matches(const nsIntSize& aSize, const SVGImageContext& aSVGContext,
47 float aFrame, uint32_t aFlags) const {
48 return mSize == aSize && mSVGContext == aSVGContext && mFrame == aFrame &&
49 mFlags == aFlags;
52 already_AddRefed<SourceSurface> Surface() const {
53 RefPtr<SourceSurface> surf(mSurface);
54 return surf.forget();
57 ImgDrawResult GetDrawResult() const { return mDrawResult; }
59 bool NeedsRedraw() const {
60 return mDrawResult != ImgDrawResult::SUCCESS &&
61 mDrawResult != ImgDrawResult::BAD_IMAGE;
64 private:
65 RefPtr<SourceSurface> mSurface;
66 const nsIntSize mSize;
67 SVGImageContext mSVGContext;
68 const float mFrame;
69 const uint32_t mFlags;
70 const ImgDrawResult mDrawResult;
73 class DrawSingleTileCallback : public gfxDrawingCallback {
74 public:
75 DrawSingleTileCallback(ClippedImage* aImage, const nsIntSize& aSize,
76 const SVGImageContext& aSVGContext,
77 uint32_t aWhichFrame, uint32_t aFlags, float aOpacity)
78 : mImage(aImage),
79 mSize(aSize),
80 mSVGContext(aSVGContext),
81 mWhichFrame(aWhichFrame),
82 mFlags(aFlags),
83 mDrawResult(ImgDrawResult::NOT_READY),
84 mOpacity(aOpacity) {
85 MOZ_ASSERT(mImage, "Must have an image to clip");
88 virtual bool operator()(gfxContext* aContext, const gfxRect& aFillRect,
89 const SamplingFilter aSamplingFilter,
90 const gfxMatrix& aTransform) override {
91 MOZ_ASSERT(aTransform.IsIdentity(),
92 "Caller is probably CreateSamplingRestrictedDrawable, "
93 "which should not happen");
95 // Draw the image. |gfxCallbackDrawable| always calls this function with
96 // arguments that guarantee we never tile.
97 mDrawResult = mImage->DrawSingleTile(
98 aContext, mSize, ImageRegion::Create(aFillRect), mWhichFrame,
99 aSamplingFilter, mSVGContext, mFlags, mOpacity);
101 return true;
104 ImgDrawResult GetDrawResult() { return mDrawResult; }
106 private:
107 RefPtr<ClippedImage> mImage;
108 const nsIntSize mSize;
109 const SVGImageContext& mSVGContext;
110 const uint32_t mWhichFrame;
111 const uint32_t mFlags;
112 ImgDrawResult mDrawResult;
113 float mOpacity;
116 ClippedImage::ClippedImage(Image* aImage, nsIntRect aClip,
117 const Maybe<nsSize>& aSVGViewportSize)
118 : ImageWrapper(aImage), mClip(aClip) {
119 MOZ_ASSERT(aImage != nullptr, "ClippedImage requires an existing Image");
120 MOZ_ASSERT_IF(aSVGViewportSize,
121 aImage->GetType() == imgIContainer::TYPE_VECTOR);
122 if (aSVGViewportSize) {
123 mSVGViewportSize =
124 Some(aSVGViewportSize->ToNearestPixels(AppUnitsPerCSSPixel()));
128 ClippedImage::~ClippedImage() {}
130 bool ClippedImage::ShouldClip() {
131 // We need to evaluate the clipping region against the image's width and
132 // height once they're available to determine if it's valid and whether we
133 // actually need to do any work. We may fail if the image's width and height
134 // aren't available yet, in which case we'll try again later.
135 if (mShouldClip.isNothing()) {
136 int32_t width, height;
137 RefPtr<ProgressTracker> progressTracker =
138 InnerImage()->GetProgressTracker();
139 if (InnerImage()->HasError()) {
140 // If there's a problem with the inner image we'll let it handle
141 // everything.
142 mShouldClip.emplace(false);
143 } else if (mSVGViewportSize && !mSVGViewportSize->IsEmpty()) {
144 // Clamp the clipping region to the size of the SVG viewport.
145 nsIntRect svgViewportRect(nsIntPoint(0, 0), *mSVGViewportSize);
147 mClip = mClip.Intersect(svgViewportRect);
149 // If the clipping region is the same size as the SVG viewport size
150 // we don't have to do anything.
151 mShouldClip.emplace(!mClip.IsEqualInterior(svgViewportRect));
152 } else if (NS_SUCCEEDED(InnerImage()->GetWidth(&width)) && width > 0 &&
153 NS_SUCCEEDED(InnerImage()->GetHeight(&height)) && height > 0) {
154 // Clamp the clipping region to the size of the underlying image.
155 mClip = mClip.Intersect(nsIntRect(0, 0, width, height));
157 // If the clipping region is the same size as the underlying image we
158 // don't have to do anything.
159 mShouldClip.emplace(
160 !mClip.IsEqualInterior(nsIntRect(0, 0, width, height)));
161 } else if (progressTracker &&
162 !(progressTracker->GetProgress() & FLAG_LOAD_COMPLETE)) {
163 // The image just hasn't finished loading yet. We don't yet know whether
164 // clipping with be needed or not for now. Just return without memorizing
165 // anything.
166 return false;
167 } else {
168 // We have a fully loaded image without a clearly defined width and
169 // height. This can happen with SVG images.
170 mShouldClip.emplace(false);
174 MOZ_ASSERT(mShouldClip.isSome(), "Should have computed a result");
175 return *mShouldClip;
178 NS_IMETHODIMP
179 ClippedImage::GetWidth(int32_t* aWidth) {
180 if (!ShouldClip()) {
181 return InnerImage()->GetWidth(aWidth);
184 *aWidth = mClip.Width();
185 return NS_OK;
188 NS_IMETHODIMP
189 ClippedImage::GetHeight(int32_t* aHeight) {
190 if (!ShouldClip()) {
191 return InnerImage()->GetHeight(aHeight);
194 *aHeight = mClip.Height();
195 return NS_OK;
198 NS_IMETHODIMP
199 ClippedImage::GetIntrinsicSize(nsSize* aSize) {
200 if (!ShouldClip()) {
201 return InnerImage()->GetIntrinsicSize(aSize);
204 *aSize = nsSize(mClip.Width(), mClip.Height());
205 return NS_OK;
208 Maybe<AspectRatio> ClippedImage::GetIntrinsicRatio() {
209 if (!ShouldClip()) {
210 return InnerImage()->GetIntrinsicRatio();
213 return Some(AspectRatio::FromSize(mClip.Width(), mClip.Height()));
216 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
217 ClippedImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
218 RefPtr<SourceSurface> surface;
219 std::tie(std::ignore, surface) = GetFrameInternal(
220 mClip.Size(), SVGImageContext(), Nothing(), aWhichFrame, aFlags, 1.0);
221 return surface.forget();
224 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
225 ClippedImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
226 uint32_t aFlags) {
227 // XXX(seth): It'd be nice to support downscale-during-decode for this case,
228 // but right now we just fall back to the intrinsic size.
229 return GetFrame(aWhichFrame, aFlags);
232 std::pair<ImgDrawResult, RefPtr<SourceSurface>> ClippedImage::GetFrameInternal(
233 const nsIntSize& aSize, const SVGImageContext& aSVGContext,
234 const Maybe<ImageIntRegion>& aRegion, uint32_t aWhichFrame, uint32_t aFlags,
235 float aOpacity) {
236 if (!ShouldClip()) {
237 RefPtr<SourceSurface> surface = InnerImage()->GetFrame(aWhichFrame, aFlags);
238 return std::make_pair(
239 surface ? ImgDrawResult::SUCCESS : ImgDrawResult::NOT_READY,
240 std::move(surface));
243 float frameToDraw = InnerImage()->GetFrameIndex(aWhichFrame);
244 if (!mCachedSurface ||
245 !mCachedSurface->Matches(aSize, aSVGContext, frameToDraw, aFlags) ||
246 mCachedSurface->NeedsRedraw()) {
247 // Create a surface to draw into.
248 RefPtr<DrawTarget> target =
249 gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
250 IntSize(aSize.width, aSize.height), SurfaceFormat::OS_RGBA);
251 if (!target || !target->IsValid()) {
252 NS_ERROR("Could not create a DrawTarget");
253 return std::make_pair(ImgDrawResult::TEMPORARY_ERROR,
254 RefPtr<SourceSurface>());
257 gfxContext ctx(target);
259 // Create our callback.
260 RefPtr<DrawSingleTileCallback> drawTileCallback =
261 new DrawSingleTileCallback(this, aSize, aSVGContext, aWhichFrame,
262 aFlags, aOpacity);
263 RefPtr<gfxDrawable> drawable =
264 new gfxCallbackDrawable(drawTileCallback, aSize);
266 // Actually draw. The callback will end up invoking DrawSingleTile.
267 gfxUtils::DrawPixelSnapped(&ctx, drawable, SizeDouble(aSize),
268 ImageRegion::Create(aSize),
269 SurfaceFormat::OS_RGBA, SamplingFilter::LINEAR,
270 imgIContainer::FLAG_CLAMP);
272 // Cache the resulting surface.
273 mCachedSurface = MakeUnique<ClippedImageCachedSurface>(
274 target->Snapshot(), aSize, aSVGContext, frameToDraw, aFlags,
275 drawTileCallback->GetDrawResult());
278 MOZ_ASSERT(mCachedSurface, "Should have a cached surface now");
279 RefPtr<SourceSurface> surface = mCachedSurface->Surface();
280 return std::make_pair(mCachedSurface->GetDrawResult(), std::move(surface));
283 NS_IMETHODIMP_(bool)
284 ClippedImage::IsImageContainerAvailable(WindowRenderer* aRenderer,
285 uint32_t aFlags) {
286 if (!ShouldClip()) {
287 return InnerImage()->IsImageContainerAvailable(aRenderer, aFlags);
289 return false;
292 NS_IMETHODIMP_(ImgDrawResult)
293 ClippedImage::GetImageProvider(WindowRenderer* aRenderer,
294 const gfx::IntSize& aSize,
295 const SVGImageContext& aSVGContext,
296 const Maybe<ImageIntRegion>& aRegion,
297 uint32_t aFlags,
298 WebRenderImageProvider** aProvider) {
299 // XXX(seth): We currently don't have a way of clipping the result of
300 // GetImageContainer. We work around this by always returning null, but if it
301 // ever turns out that ClippedImage is widely used on codepaths that can
302 // actually benefit from GetImageContainer, it would be a good idea to fix
303 // that method for performance reasons.
305 if (!ShouldClip()) {
306 return InnerImage()->GetImageProvider(aRenderer, aSize, aSVGContext,
307 aRegion, aFlags, aProvider);
310 return ImgDrawResult::NOT_SUPPORTED;
313 static bool MustCreateSurface(gfxContext* aContext, const nsIntSize& aSize,
314 const ImageRegion& aRegion,
315 const uint32_t aFlags) {
316 gfxRect imageRect(0, 0, aSize.width, aSize.height);
317 bool willTile = !imageRect.Contains(aRegion.Rect()) &&
318 !(aFlags & imgIContainer::FLAG_CLAMP);
319 bool willResample = aContext->CurrentMatrix().HasNonIntegerTranslation() &&
320 (willTile || !aRegion.RestrictionContains(imageRect));
321 return willTile || willResample;
324 NS_IMETHODIMP_(ImgDrawResult)
325 ClippedImage::Draw(gfxContext* aContext, const nsIntSize& aSize,
326 const ImageRegion& aRegion, uint32_t aWhichFrame,
327 SamplingFilter aSamplingFilter,
328 const SVGImageContext& aSVGContext, uint32_t aFlags,
329 float aOpacity) {
330 if (!ShouldClip()) {
331 return InnerImage()->Draw(aContext, aSize, aRegion, aWhichFrame,
332 aSamplingFilter, aSVGContext, aFlags, aOpacity);
335 // Check for tiling. If we need to tile then we need to create a
336 // gfxCallbackDrawable to handle drawing for us.
337 if (MustCreateSurface(aContext, aSize, aRegion, aFlags)) {
338 // Create a temporary surface containing a single tile of this image.
339 // GetFrame will call DrawSingleTile internally.
340 auto [result, surface] = GetFrameInternal(aSize, aSVGContext, Nothing(),
341 aWhichFrame, aFlags, aOpacity);
342 if (!surface) {
343 MOZ_ASSERT(result != ImgDrawResult::SUCCESS);
344 return result;
347 // Create a drawable from that surface.
348 RefPtr<gfxSurfaceDrawable> drawable =
349 new gfxSurfaceDrawable(surface, aSize);
351 // Draw.
352 gfxUtils::DrawPixelSnapped(aContext, drawable, SizeDouble(aSize), aRegion,
353 SurfaceFormat::OS_RGBA, aSamplingFilter,
354 aOpacity);
356 return result;
359 return DrawSingleTile(aContext, aSize, aRegion, aWhichFrame, aSamplingFilter,
360 aSVGContext, aFlags, aOpacity);
363 ImgDrawResult ClippedImage::DrawSingleTile(
364 gfxContext* aContext, const nsIntSize& aSize, const ImageRegion& aRegion,
365 uint32_t aWhichFrame, SamplingFilter aSamplingFilter,
366 const SVGImageContext& aSVGContext, uint32_t aFlags, float aOpacity) {
367 MOZ_ASSERT(!MustCreateSurface(aContext, aSize, aRegion, aFlags),
368 "Shouldn't need to create a surface");
370 gfxRect clip(mClip.X(), mClip.Y(), mClip.Width(), mClip.Height());
371 nsIntSize size(aSize), innerSize(aSize);
372 bool needScale = false;
373 if (mSVGViewportSize && !mSVGViewportSize->IsEmpty()) {
374 innerSize = *mSVGViewportSize;
375 needScale = true;
376 } else if (NS_SUCCEEDED(InnerImage()->GetWidth(&innerSize.width)) &&
377 NS_SUCCEEDED(InnerImage()->GetHeight(&innerSize.height))) {
378 needScale = true;
379 } else {
380 MOZ_ASSERT_UNREACHABLE(
381 "If ShouldClip() led us to draw then we should never get here");
384 if (needScale) {
385 double scaleX = aSize.width / clip.Width();
386 double scaleY = aSize.height / clip.Height();
388 // Map the clip and size to the scale requested by the caller.
389 clip.Scale(scaleX, scaleY);
390 size = innerSize;
391 size.Scale(scaleX, scaleY);
394 // We restrict our drawing to only the clipping region, and translate so that
395 // the clipping region is placed at the position the caller expects.
396 ImageRegion region(aRegion);
397 region.MoveBy(clip.X(), clip.Y());
398 region = region.Intersect(clip);
400 gfxContextMatrixAutoSaveRestore saveMatrix(aContext);
401 aContext->Multiply(gfxMatrix::Translation(-clip.X(), -clip.Y()));
403 auto unclipViewport = [&](const SVGImageContext& aOldContext) {
404 // Map the viewport to the inner image. Note that we don't take the aSize
405 // parameter of imgIContainer::Draw into account, just the clipping region.
406 // The size in pixels at which the output will ultimately be drawn is
407 // irrelevant here since the purpose of the SVG viewport size is to
408 // determine what *region* of the SVG document will be drawn.
409 SVGImageContext context(aOldContext);
410 auto oldViewport = aOldContext.GetViewportSize();
411 if (oldViewport) {
412 CSSIntSize newViewport;
413 newViewport.width =
414 ceil(oldViewport->width * double(innerSize.width) / mClip.Width());
415 newViewport.height =
416 ceil(oldViewport->height * double(innerSize.height) / mClip.Height());
417 context.SetViewportSize(Some(newViewport));
419 return context;
422 return InnerImage()->Draw(aContext, size, region, aWhichFrame,
423 aSamplingFilter, unclipViewport(aSVGContext),
424 aFlags, aOpacity);
427 NS_IMETHODIMP
428 ClippedImage::RequestDiscard() {
429 // We're very aggressive about discarding.
430 mCachedSurface = nullptr;
432 return InnerImage()->RequestDiscard();
435 NS_IMETHODIMP_(Orientation)
436 ClippedImage::GetOrientation() {
437 // XXX(seth): This should not actually be here; this is just to work around a
438 // what appears to be a bug in MSVC's linker.
439 return InnerImage()->GetOrientation();
442 nsIntSize ClippedImage::OptimalImageSizeForDest(const gfxSize& aDest,
443 uint32_t aWhichFrame,
444 SamplingFilter aSamplingFilter,
445 uint32_t aFlags) {
446 if (!ShouldClip()) {
447 return InnerImage()->OptimalImageSizeForDest(aDest, aWhichFrame,
448 aSamplingFilter, aFlags);
451 int32_t imgWidth, imgHeight;
452 bool needScale = false;
453 bool forceUniformScaling = false;
454 if (mSVGViewportSize && !mSVGViewportSize->IsEmpty()) {
455 imgWidth = mSVGViewportSize->width;
456 imgHeight = mSVGViewportSize->height;
457 needScale = true;
458 forceUniformScaling = (aFlags & imgIContainer::FLAG_FORCE_UNIFORM_SCALING);
459 } else if (NS_SUCCEEDED(InnerImage()->GetWidth(&imgWidth)) &&
460 NS_SUCCEEDED(InnerImage()->GetHeight(&imgHeight))) {
461 needScale = true;
464 if (needScale) {
465 // To avoid ugly sampling artifacts, ClippedImage needs the image size to
466 // be chosen such that the clipping region lies on pixel boundaries.
468 // First, we select a scale that's good for ClippedImage. An integer
469 // multiple of the size of the clipping region is always fine.
470 IntSize scale = IntSize::Ceil(aDest.width / mClip.Width(),
471 aDest.height / mClip.Height());
473 if (forceUniformScaling) {
474 scale.width = scale.height = max(scale.height, scale.width);
477 // Determine the size we'd prefer to render the inner image at, and ask the
478 // inner image what size we should actually use.
479 gfxSize desiredSize(double(imgWidth) * scale.width,
480 double(imgHeight) * scale.height);
481 nsIntSize innerDesiredSize = InnerImage()->OptimalImageSizeForDest(
482 desiredSize, aWhichFrame, aSamplingFilter, aFlags);
484 // To get our final result, we take the inner image's desired size and
485 // determine how large the clipped region would be at that scale. (Again, we
486 // ensure an integer multiple of the size of the clipping region.)
487 IntSize finalScale =
488 IntSize::Ceil(double(innerDesiredSize.width) / imgWidth,
489 double(innerDesiredSize.height) / imgHeight);
490 return mClip.Size() * finalScale;
493 MOZ_ASSERT(false,
494 "If ShouldClip() led us to draw then we should never get here");
495 return InnerImage()->OptimalImageSizeForDest(aDest, aWhichFrame,
496 aSamplingFilter, aFlags);
499 NS_IMETHODIMP_(nsIntRect)
500 ClippedImage::GetImageSpaceInvalidationRect(const nsIntRect& aRect) {
501 if (!ShouldClip()) {
502 return InnerImage()->GetImageSpaceInvalidationRect(aRect);
505 nsIntRect rect(InnerImage()->GetImageSpaceInvalidationRect(aRect));
506 rect = rect.Intersect(mClip);
507 rect.MoveBy(-mClip.X(), -mClip.Y());
508 return rect;
511 } // namespace image
512 } // namespace mozilla