Bug 1931736. Add missing braces around if/loop statements in layout/xul/. r=layout...
[gecko.git] / image / ClippedImage.cpp
blobcdd2c569fb743a2adbff07c74187f47590dc22ad
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 AspectRatio ClippedImage::GetIntrinsicRatio() {
209 if (!ShouldClip()) {
210 return InnerImage()->GetIntrinsicRatio();
212 return AspectRatio::FromSize(mClip.Width(), mClip.Height());
215 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
216 ClippedImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
217 RefPtr<SourceSurface> surface;
218 std::tie(std::ignore, surface) = GetFrameInternal(
219 mClip.Size(), SVGImageContext(), Nothing(), aWhichFrame, aFlags, 1.0);
220 return surface.forget();
223 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
224 ClippedImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
225 uint32_t aFlags) {
226 // XXX(seth): It'd be nice to support downscale-during-decode for this case,
227 // but right now we just fall back to the intrinsic size.
228 return GetFrame(aWhichFrame, aFlags);
231 std::pair<ImgDrawResult, RefPtr<SourceSurface>> ClippedImage::GetFrameInternal(
232 const nsIntSize& aSize, const SVGImageContext& aSVGContext,
233 const Maybe<ImageIntRegion>& aRegion, uint32_t aWhichFrame, uint32_t aFlags,
234 float aOpacity) {
235 if (!ShouldClip()) {
236 RefPtr<SourceSurface> surface = InnerImage()->GetFrame(aWhichFrame, aFlags);
237 return std::make_pair(
238 surface ? ImgDrawResult::SUCCESS : ImgDrawResult::NOT_READY,
239 std::move(surface));
242 float frameToDraw = InnerImage()->GetFrameIndex(aWhichFrame);
243 if (!mCachedSurface ||
244 !mCachedSurface->Matches(aSize, aSVGContext, frameToDraw, aFlags) ||
245 mCachedSurface->NeedsRedraw()) {
246 // Create a surface to draw into.
247 RefPtr<DrawTarget> target =
248 gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
249 IntSize(aSize.width, aSize.height), SurfaceFormat::OS_RGBA);
250 if (!target || !target->IsValid()) {
251 NS_ERROR("Could not create a DrawTarget");
252 return std::make_pair(ImgDrawResult::TEMPORARY_ERROR,
253 RefPtr<SourceSurface>());
256 gfxContext ctx(target);
258 // Create our callback.
259 RefPtr<DrawSingleTileCallback> drawTileCallback =
260 new DrawSingleTileCallback(this, aSize, aSVGContext, aWhichFrame,
261 aFlags, aOpacity);
262 RefPtr<gfxDrawable> drawable =
263 new gfxCallbackDrawable(drawTileCallback, aSize);
265 // Actually draw. The callback will end up invoking DrawSingleTile.
266 gfxUtils::DrawPixelSnapped(&ctx, drawable, SizeDouble(aSize),
267 ImageRegion::Create(aSize),
268 SurfaceFormat::OS_RGBA, SamplingFilter::LINEAR,
269 imgIContainer::FLAG_CLAMP);
271 // Cache the resulting surface.
272 mCachedSurface = MakeUnique<ClippedImageCachedSurface>(
273 target->Snapshot(), aSize, aSVGContext, frameToDraw, aFlags,
274 drawTileCallback->GetDrawResult());
277 MOZ_ASSERT(mCachedSurface, "Should have a cached surface now");
278 RefPtr<SourceSurface> surface = mCachedSurface->Surface();
279 return std::make_pair(mCachedSurface->GetDrawResult(), std::move(surface));
282 NS_IMETHODIMP_(bool)
283 ClippedImage::IsImageContainerAvailable(WindowRenderer* aRenderer,
284 uint32_t aFlags) {
285 if (!ShouldClip()) {
286 return InnerImage()->IsImageContainerAvailable(aRenderer, aFlags);
288 return false;
291 NS_IMETHODIMP_(ImgDrawResult)
292 ClippedImage::GetImageProvider(WindowRenderer* aRenderer,
293 const gfx::IntSize& aSize,
294 const SVGImageContext& aSVGContext,
295 const Maybe<ImageIntRegion>& aRegion,
296 uint32_t aFlags,
297 WebRenderImageProvider** aProvider) {
298 // XXX(seth): We currently don't have a way of clipping the result of
299 // GetImageContainer. We work around this by always returning null, but if it
300 // ever turns out that ClippedImage is widely used on codepaths that can
301 // actually benefit from GetImageContainer, it would be a good idea to fix
302 // that method for performance reasons.
304 if (!ShouldClip()) {
305 return InnerImage()->GetImageProvider(aRenderer, aSize, aSVGContext,
306 aRegion, aFlags, aProvider);
309 return ImgDrawResult::NOT_SUPPORTED;
312 static bool MustCreateSurface(gfxContext* aContext, const nsIntSize& aSize,
313 const ImageRegion& aRegion,
314 const uint32_t aFlags) {
315 gfxRect imageRect(0, 0, aSize.width, aSize.height);
316 bool willTile = !imageRect.Contains(aRegion.Rect()) &&
317 !(aFlags & imgIContainer::FLAG_CLAMP);
318 bool willResample = aContext->CurrentMatrix().HasNonIntegerTranslation() &&
319 (willTile || !aRegion.RestrictionContains(imageRect));
320 return willTile || willResample;
323 NS_IMETHODIMP_(ImgDrawResult)
324 ClippedImage::Draw(gfxContext* aContext, const nsIntSize& aSize,
325 const ImageRegion& aRegion, uint32_t aWhichFrame,
326 SamplingFilter aSamplingFilter,
327 const SVGImageContext& aSVGContext, uint32_t aFlags,
328 float aOpacity) {
329 if (!ShouldClip()) {
330 return InnerImage()->Draw(aContext, aSize, aRegion, aWhichFrame,
331 aSamplingFilter, aSVGContext, aFlags, aOpacity);
334 // Check for tiling. If we need to tile then we need to create a
335 // gfxCallbackDrawable to handle drawing for us.
336 if (MustCreateSurface(aContext, aSize, aRegion, aFlags)) {
337 // Create a temporary surface containing a single tile of this image.
338 // GetFrame will call DrawSingleTile internally.
339 auto [result, surface] = GetFrameInternal(aSize, aSVGContext, Nothing(),
340 aWhichFrame, aFlags, aOpacity);
341 if (!surface) {
342 MOZ_ASSERT(result != ImgDrawResult::SUCCESS);
343 return result;
346 // Create a drawable from that surface.
347 RefPtr<gfxSurfaceDrawable> drawable =
348 new gfxSurfaceDrawable(surface, aSize);
350 // Draw.
351 gfxUtils::DrawPixelSnapped(aContext, drawable, SizeDouble(aSize), aRegion,
352 SurfaceFormat::OS_RGBA, aSamplingFilter,
353 aOpacity);
355 return result;
358 return DrawSingleTile(aContext, aSize, aRegion, aWhichFrame, aSamplingFilter,
359 aSVGContext, aFlags, aOpacity);
362 ImgDrawResult ClippedImage::DrawSingleTile(
363 gfxContext* aContext, const nsIntSize& aSize, const ImageRegion& aRegion,
364 uint32_t aWhichFrame, SamplingFilter aSamplingFilter,
365 const SVGImageContext& aSVGContext, uint32_t aFlags, float aOpacity) {
366 MOZ_ASSERT(!MustCreateSurface(aContext, aSize, aRegion, aFlags),
367 "Shouldn't need to create a surface");
369 gfxRect clip(mClip.X(), mClip.Y(), mClip.Width(), mClip.Height());
370 nsIntSize size(aSize), innerSize(aSize);
371 bool needScale = false;
372 if (mSVGViewportSize && !mSVGViewportSize->IsEmpty()) {
373 innerSize = *mSVGViewportSize;
374 needScale = true;
375 } else if (NS_SUCCEEDED(InnerImage()->GetWidth(&innerSize.width)) &&
376 NS_SUCCEEDED(InnerImage()->GetHeight(&innerSize.height))) {
377 needScale = true;
378 } else {
379 MOZ_ASSERT_UNREACHABLE(
380 "If ShouldClip() led us to draw then we should never get here");
383 if (needScale) {
384 double scaleX = aSize.width / clip.Width();
385 double scaleY = aSize.height / clip.Height();
387 // Map the clip and size to the scale requested by the caller.
388 clip.Scale(scaleX, scaleY);
389 size = innerSize;
390 size.Scale(scaleX, scaleY);
393 // We restrict our drawing to only the clipping region, and translate so that
394 // the clipping region is placed at the position the caller expects.
395 ImageRegion region(aRegion);
396 region.MoveBy(clip.X(), clip.Y());
397 region = region.Intersect(clip);
399 gfxContextMatrixAutoSaveRestore saveMatrix(aContext);
400 aContext->Multiply(gfxMatrix::Translation(-clip.X(), -clip.Y()));
402 auto unclipViewport = [&](const SVGImageContext& aOldContext) {
403 // Map the viewport to the inner image. Note that we don't take the aSize
404 // parameter of imgIContainer::Draw into account, just the clipping region.
405 // The size in pixels at which the output will ultimately be drawn is
406 // irrelevant here since the purpose of the SVG viewport size is to
407 // determine what *region* of the SVG document will be drawn.
408 SVGImageContext context(aOldContext);
409 auto oldViewport = aOldContext.GetViewportSize();
410 if (oldViewport) {
411 CSSIntSize newViewport;
412 newViewport.width =
413 ceil(oldViewport->width * double(innerSize.width) / mClip.Width());
414 newViewport.height =
415 ceil(oldViewport->height * double(innerSize.height) / mClip.Height());
416 context.SetViewportSize(Some(newViewport));
418 return context;
421 return InnerImage()->Draw(aContext, size, region, aWhichFrame,
422 aSamplingFilter, unclipViewport(aSVGContext),
423 aFlags, aOpacity);
426 NS_IMETHODIMP
427 ClippedImage::RequestDiscard() {
428 // We're very aggressive about discarding.
429 mCachedSurface = nullptr;
431 return InnerImage()->RequestDiscard();
434 NS_IMETHODIMP_(Orientation)
435 ClippedImage::GetOrientation() {
436 // XXX(seth): This should not actually be here; this is just to work around a
437 // what appears to be a bug in MSVC's linker.
438 return InnerImage()->GetOrientation();
441 nsIntSize ClippedImage::OptimalImageSizeForDest(const gfxSize& aDest,
442 uint32_t aWhichFrame,
443 SamplingFilter aSamplingFilter,
444 uint32_t aFlags) {
445 if (!ShouldClip()) {
446 return InnerImage()->OptimalImageSizeForDest(aDest, aWhichFrame,
447 aSamplingFilter, aFlags);
450 int32_t imgWidth, imgHeight;
451 bool needScale = false;
452 bool forceUniformScaling = false;
453 if (mSVGViewportSize && !mSVGViewportSize->IsEmpty()) {
454 imgWidth = mSVGViewportSize->width;
455 imgHeight = mSVGViewportSize->height;
456 needScale = true;
457 forceUniformScaling = (aFlags & imgIContainer::FLAG_FORCE_UNIFORM_SCALING);
458 } else if (NS_SUCCEEDED(InnerImage()->GetWidth(&imgWidth)) &&
459 NS_SUCCEEDED(InnerImage()->GetHeight(&imgHeight))) {
460 needScale = true;
463 if (needScale) {
464 // To avoid ugly sampling artifacts, ClippedImage needs the image size to
465 // be chosen such that the clipping region lies on pixel boundaries.
467 // First, we select a scale that's good for ClippedImage. An integer
468 // multiple of the size of the clipping region is always fine.
469 IntSize scale = IntSize::Ceil(aDest.width / mClip.Width(),
470 aDest.height / mClip.Height());
472 if (forceUniformScaling) {
473 scale.width = scale.height = max(scale.height, scale.width);
476 // Determine the size we'd prefer to render the inner image at, and ask the
477 // inner image what size we should actually use.
478 gfxSize desiredSize(double(imgWidth) * scale.width,
479 double(imgHeight) * scale.height);
480 nsIntSize innerDesiredSize = InnerImage()->OptimalImageSizeForDest(
481 desiredSize, aWhichFrame, aSamplingFilter, aFlags);
483 // To get our final result, we take the inner image's desired size and
484 // determine how large the clipped region would be at that scale. (Again, we
485 // ensure an integer multiple of the size of the clipping region.)
486 IntSize finalScale =
487 IntSize::Ceil(double(innerDesiredSize.width) / imgWidth,
488 double(innerDesiredSize.height) / imgHeight);
489 return mClip.Size() * finalScale;
492 MOZ_ASSERT(false,
493 "If ShouldClip() led us to draw then we should never get here");
494 return InnerImage()->OptimalImageSizeForDest(aDest, aWhichFrame,
495 aSamplingFilter, aFlags);
498 NS_IMETHODIMP_(nsIntRect)
499 ClippedImage::GetImageSpaceInvalidationRect(const nsIntRect& aRect) {
500 if (!ShouldClip()) {
501 return InnerImage()->GetImageSpaceInvalidationRect(aRect);
504 nsIntRect rect(InnerImage()->GetImageSpaceInvalidationRect(aRect));
505 rect = rect.Intersect(mClip);
506 rect.MoveBy(-mClip.X(), -mClip.Y());
507 return rect;
510 } // namespace image
511 } // namespace mozilla