2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2000 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Allan Sandfeld Jensen (kde@carewolf.com)
6 * (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
7 * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
8 * Copyright (C) 2010 Google Inc. All rights reserved.
9 * Copyright (C) Research In Motion Limited 2011-2012. All rights reserved.
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
29 #include "RenderImage.h"
31 #include "AXObjectCache.h"
32 #include "BitmapImage.h"
33 #include "CachedImage.h"
34 #include "FocusController.h"
35 #include "FontCache.h"
36 #include "FontCascade.h"
38 #include "FrameSelection.h"
39 #include "GeometryUtilities.h"
40 #include "GraphicsContext.h"
41 #include "HTMLAreaElement.h"
42 #include "HTMLImageElement.h"
43 #include "HTMLInputElement.h"
44 #include "HTMLMapElement.h"
45 #include "HTMLNames.h"
46 #include "HitTestResult.h"
47 #include "InlineElementBox.h"
49 #include "PaintInfo.h"
50 #include "RenderFlowThread.h"
51 #include "RenderImageResourceStyleImage.h"
52 #include "RenderView.h"
54 #include <wtf/StackStats.h>
57 #include "LogicalSelectionOffsetCaches.h"
58 #include "SelectionRect.h"
62 #include "PDFDocumentImage.h"
69 // FIXME: This doesn't behave correctly for floating or positioned images, but WebCore doesn't handle those well
70 // during selection creation yet anyway.
71 // FIXME: We can't tell whether or not we contain the start or end of the selected Range using only the offsets
72 // of the start and end, we need to know the whole Position.
73 void RenderImage::collectSelectionRects(Vector<SelectionRect>& rects, unsigned, unsigned)
75 RenderBlock* containingBlock = this->containingBlock();
78 // FIXME: It doesn't make sense to package line bounds into SelectionRects. We should find
79 // the right and left extent of the selection once for the entire selected Range, perhaps
80 // using the Range's common ancestor.
81 IntRect lineExtentRect;
82 bool isFirstOnLine = false;
83 bool isLastOnLine = false;
85 InlineBox* inlineBox = inlineBoxWrapper();
87 // This is a block image.
88 imageRect = IntRect(0, 0, width(), height());
91 lineExtentRect = imageRect;
92 if (containingBlock->isHorizontalWritingMode()) {
93 lineExtentRect.setX(containingBlock->x());
94 lineExtentRect.setWidth(containingBlock->width());
96 lineExtentRect.setY(containingBlock->y());
97 lineExtentRect.setHeight(containingBlock->height());
100 LayoutUnit selectionTop = !containingBlock->style().isFlippedBlocksWritingMode() ? inlineBox->root().selectionTop() - logicalTop() : logicalBottom() - inlineBox->root().selectionBottom();
101 imageRect = IntRect(0, selectionTop, logicalWidth(), inlineBox->root().selectionHeight());
102 isFirstOnLine = !inlineBox->previousOnLineExists();
103 isLastOnLine = !inlineBox->nextOnLineExists();
104 LogicalSelectionOffsetCaches cache(*containingBlock);
105 LayoutUnit leftOffset = containingBlock->logicalLeftSelectionOffset(*containingBlock, inlineBox->logicalTop(), cache);
106 LayoutUnit rightOffset = containingBlock->logicalRightSelectionOffset(*containingBlock, inlineBox->logicalTop(), cache);
107 lineExtentRect = IntRect(leftOffset - logicalLeft(), imageRect.y(), rightOffset - leftOffset, imageRect.height());
108 if (!inlineBox->isHorizontal()) {
109 imageRect = imageRect.transposedRect();
110 lineExtentRect = lineExtentRect.transposedRect();
114 bool isFixed = false;
115 IntRect absoluteBounds = localToAbsoluteQuad(FloatRect(imageRect), UseTransforms, &isFixed).enclosingBoundingBox();
116 IntRect lineExtentBounds = localToAbsoluteQuad(FloatRect(lineExtentRect)).enclosingBoundingBox();
117 if (!containingBlock->isHorizontalWritingMode())
118 lineExtentBounds = lineExtentBounds.transposedRect();
120 // FIXME: We should consider either making SelectionRect a struct or better organize its optional fields into
121 // an auxiliary struct to simplify its initialization.
122 rects.append(SelectionRect(absoluteBounds, containingBlock->style().direction(), lineExtentBounds.x(), lineExtentBounds.maxX(), lineExtentBounds.maxY(), 0, false /* line break */, isFirstOnLine, isLastOnLine, false /* contains start */, false /* contains end */, containingBlock->style().isHorizontalWritingMode(), isFixed, false /* ruby text */, view().pageNumberForBlockProgressionOffset(absoluteBounds.x())));
126 using namespace HTMLNames;
128 RenderImage::RenderImage(Element& element, RenderStyle&& style, StyleImage* styleImage, const float imageDevicePixelRatio)
129 : RenderReplaced(element, WTFMove(style), IntSize())
130 , m_imageResource(styleImage ? std::make_unique<RenderImageResourceStyleImage>(*styleImage) : std::make_unique<RenderImageResource>())
131 , m_imageDevicePixelRatio(imageDevicePixelRatio)
134 if (is<HTMLImageElement>(element))
135 m_hasShadowControls = downcast<HTMLImageElement>(element).hasShadowControls();
138 RenderImage::RenderImage(Document& document, RenderStyle&& style, StyleImage* styleImage)
139 : RenderReplaced(document, WTFMove(style), IntSize())
140 , m_imageResource(styleImage ? std::make_unique<RenderImageResourceStyleImage>(*styleImage) : std::make_unique<RenderImageResource>())
144 RenderImage::~RenderImage()
146 // Do not add any code here. Add it to willBeDestroyed() instead.
149 void RenderImage::willBeDestroyed()
151 imageResource().shutdown();
152 RenderReplaced::willBeDestroyed();
155 // If we'll be displaying either alt text or an image, add some padding.
156 static const unsigned short paddingWidth = 4;
157 static const unsigned short paddingHeight = 4;
159 // Alt text is restricted to this maximum size, in pixels. These are
160 // signed integers because they are compared with other signed values.
161 static const float maxAltTextWidth = 1024;
162 static const int maxAltTextHeight = 256;
164 IntSize RenderImage::imageSizeForError(CachedImage* newImage) const
166 ASSERT_ARG(newImage, newImage);
167 ASSERT_ARG(newImage, newImage->imageForRenderer(this));
170 if (newImage->willPaintBrokenImage()) {
171 std::pair<Image*, float> brokenImageAndImageScaleFactor = newImage->brokenImage(document().deviceScaleFactor());
172 imageSize = brokenImageAndImageScaleFactor.first->size();
173 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
175 imageSize = newImage->imageForRenderer(this)->size();
177 // imageSize() returns 0 for the error image. We need the true size of the
178 // error image, so we have to get it by grabbing image() directly.
179 return IntSize(paddingWidth + imageSize.width() * style().effectiveZoom(), paddingHeight + imageSize.height() * style().effectiveZoom());
182 // Sets the image height and width to fit the alt text. Returns true if the
183 // image size changed.
184 ImageSizeChangeType RenderImage::setImageSizeForAltText(CachedImage* newImage /* = 0 */)
187 if (newImage && newImage->imageForRenderer(this))
188 imageSize = imageSizeForError(newImage);
189 else if (!m_altText.isEmpty() || newImage) {
190 // If we'll be displaying either text or an image, add a little padding.
191 imageSize = IntSize(paddingWidth, paddingHeight);
194 // we have an alt and the user meant it (its not a text we invented)
195 if (!m_altText.isEmpty()) {
196 const FontCascade& font = style().fontCascade();
197 IntSize paddedTextSize(paddingWidth + std::min(ceilf(font.width(RenderBlock::constructTextRun(m_altText, style()))), maxAltTextWidth), paddingHeight + std::min(font.fontMetrics().height(), maxAltTextHeight));
198 imageSize = imageSize.expandedTo(paddedTextSize);
201 if (imageSize == intrinsicSize())
202 return ImageSizeChangeNone;
204 setIntrinsicSize(imageSize);
205 return ImageSizeChangeForAltText;
208 void RenderImage::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
210 if (!hasInitializedStyle())
211 imageResource().initialize(*this);
212 RenderReplaced::styleWillChange(diff, newStyle);
215 void RenderImage::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
217 RenderReplaced::styleDidChange(diff, oldStyle);
218 if (m_needsToSetSizeForAltText) {
219 if (!m_altText.isEmpty() && setImageSizeForAltText(cachedImage()))
220 repaintOrMarkForLayout(ImageSizeChangeForAltText);
221 m_needsToSetSizeForAltText = false;
223 #if ENABLE(CSS_IMAGE_ORIENTATION)
224 if (diff == StyleDifferenceLayout && oldStyle->imageOrientation() != style().imageOrientation())
225 return repaintOrMarkForLayout(ImageSizeChangeNone);
228 #if ENABLE(CSS_IMAGE_RESOLUTION)
229 if (diff == StyleDifferenceLayout
230 && (oldStyle->imageResolution() != style().imageResolution()
231 || oldStyle->imageResolutionSnap() != style().imageResolutionSnap()
232 || oldStyle->imageResolutionSource() != style().imageResolutionSource()))
233 repaintOrMarkForLayout(ImageSizeChangeNone);
237 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
239 if (renderTreeBeingDestroyed())
242 if (hasVisibleBoxDecorations() || hasMask() || hasShapeOutside())
243 RenderReplaced::imageChanged(newImage, rect);
245 if (newImage != imageResource().imagePtr() || !newImage)
248 if (!m_didIncrementVisuallyNonEmptyPixelCount) {
249 // At a zoom level of 1 the image is guaranteed to have an integer size.
250 view().frameView().incrementVisuallyNonEmptyPixelCount(flooredIntSize(imageResource().imageSize(1.0f)));
251 m_didIncrementVisuallyNonEmptyPixelCount = true;
254 ImageSizeChangeType imageSizeChange = ImageSizeChangeNone;
256 // Set image dimensions, taking into account the size of the alt text.
257 if (imageResource().errorOccurred()) {
258 if (!m_altText.isEmpty() && document().hasPendingStyleRecalc()) {
261 m_needsToSetSizeForAltText = true;
262 element()->invalidateStyleAndLayerComposition();
266 imageSizeChange = setImageSizeForAltText(cachedImage());
269 if (UNLIKELY(AXObjectCache::accessibilityEnabled())) {
270 if (AXObjectCache* cache = document().existingAXObjectCache())
271 cache->recomputeIsIgnored(this);
274 repaintOrMarkForLayout(imageSizeChange, rect);
277 void RenderImage::updateIntrinsicSizeIfNeeded(const LayoutSize& newSize)
279 if (imageResource().errorOccurred() || !m_imageResource->cachedImage())
281 setIntrinsicSize(newSize);
284 void RenderImage::updateInnerContentRect()
286 // Propagate container size to image resource.
287 IntSize containerSize(replacedContentRect(intrinsicSize()).size());
288 if (!containerSize.isEmpty())
289 imageResource().setContainerSizeForRenderer(containerSize);
292 void RenderImage::repaintOrMarkForLayout(ImageSizeChangeType imageSizeChange, const IntRect* rect)
294 #if ENABLE(CSS_IMAGE_RESOLUTION)
295 double scale = style().imageResolution();
296 if (style().imageResolutionSnap() == ImageResolutionSnapPixels)
297 scale = roundForImpreciseConversion<int>(scale);
300 LayoutSize newIntrinsicSize = imageResource().intrinsicSize(style().effectiveZoom() / scale);
302 LayoutSize newIntrinsicSize = imageResource().intrinsicSize(style().effectiveZoom());
304 LayoutSize oldIntrinsicSize = intrinsicSize();
306 updateIntrinsicSizeIfNeeded(newIntrinsicSize);
308 // In the case of generated image content using :before/:after/content, we might not be
309 // in the render tree yet. In that case, we just need to update our intrinsic size.
310 // layout() will be called after we are inserted in the tree which will take care of
311 // what we are doing here.
312 if (!containingBlock())
315 bool imageSourceHasChangedSize = oldIntrinsicSize != newIntrinsicSize || imageSizeChange != ImageSizeChangeNone;
317 if (imageSourceHasChangedSize && setNeedsLayoutIfNeededAfterIntrinsicSizeChange())
320 if (everHadLayout() && !selfNeedsLayout()) {
321 // The inner content rectangle is calculated during layout, but may need an update now
322 // (unless the box has already been scheduled for layout). In order to calculate it, we
323 // may need values from the containing block, though, so make sure that we're not too
324 // early. It may be that layout hasn't even taken place once yet.
326 // FIXME: we should not have to trigger another call to setContainerSizeForRenderer()
327 // from here, since it's already being done during layout.
328 updateInnerContentRect();
331 LayoutRect repaintRect = contentBoxRect();
333 // The image changed rect is in source image coordinates (pre-zooming),
334 // so map from the bounds of the image to the contentsBox.
335 repaintRect.intersect(enclosingIntRect(mapRect(*rect, FloatRect(FloatPoint(), imageResource().imageSize(1.0f)), repaintRect)));
338 repaintRectangle(repaintRect);
340 // Tell any potential compositing layers that the image needs updating.
341 contentChanged(ImageChanged);
344 void RenderImage::notifyFinished(CachedResource& newImage)
346 if (renderTreeBeingDestroyed())
349 invalidateBackgroundObscurationStatus();
351 if (&newImage == cachedImage()) {
352 // tell any potential compositing layers
353 // that the image is done and they can reference it directly.
354 contentChanged(ImageChanged);
358 bool RenderImage::isShowingMissingOrImageError() const
360 return !imageResource().cachedImage() || imageResource().errorOccurred();
363 bool RenderImage::isShowingAltText() const
365 return isShowingMissingOrImageError() && !m_altText.isEmpty();
368 bool RenderImage::hasNonBitmapImage() const
370 if (!imageResource().cachedImage())
373 Image* image = cachedImage()->imageForRenderer(this);
374 return image && !is<BitmapImage>(image);
377 void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
379 LayoutSize contentSize = this->contentSize();
381 GraphicsContext& context = paintInfo.context();
382 float deviceScaleFactor = document().deviceScaleFactor();
384 if (!imageResource().cachedImage() || imageResource().errorOccurred()) {
385 if (paintInfo.phase == PaintPhaseSelection)
388 if (paintInfo.phase == PaintPhaseForeground)
389 page().addRelevantUnpaintedObject(this, visualOverflowRect());
391 if (contentSize.width() > 2 && contentSize.height() > 2) {
392 LayoutUnit borderWidth = LayoutUnit(1 / deviceScaleFactor);
394 LayoutUnit leftBorder = borderLeft();
395 LayoutUnit topBorder = borderTop();
396 LayoutUnit leftPad = paddingLeft();
397 LayoutUnit topPad = paddingTop();
399 // Draw an outline rect where the image should be.
400 context.setStrokeStyle(SolidStroke);
401 context.setStrokeColor(Color::lightGray);
402 context.setFillColor(Color::transparent);
403 context.drawRect(snapRectToDevicePixels(LayoutRect({ paintOffset.x() + leftBorder + leftPad, paintOffset.y() + topBorder + topPad }, contentSize), deviceScaleFactor), borderWidth);
405 bool errorPictureDrawn = false;
406 LayoutSize imageOffset;
407 // When calculating the usable dimensions, exclude the pixels of
408 // the ouline rect so the error image/alt text doesn't draw on it.
409 LayoutSize usableSize = contentSize - LayoutSize(2 * borderWidth, 2 * borderWidth);
411 RefPtr<Image> image = imageResource().image();
413 if (imageResource().errorOccurred() && !image->isNull() && usableSize.width() >= image->width() && usableSize.height() >= image->height()) {
414 // Call brokenImage() explicitly to ensure we get the broken image icon at the appropriate resolution.
415 std::pair<Image*, float> brokenImageAndImageScaleFactor = cachedImage()->brokenImage(document().deviceScaleFactor());
416 image = brokenImageAndImageScaleFactor.first;
417 FloatSize imageSize = image->size();
418 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
419 // Center the error image, accounting for border and padding.
420 LayoutUnit centerX = (usableSize.width() - imageSize.width()) / 2;
423 LayoutUnit centerY = (usableSize.height() - imageSize.height()) / 2;
426 imageOffset = LayoutSize(leftBorder + leftPad + centerX + borderWidth, topBorder + topPad + centerY + borderWidth);
428 ImageOrientationDescription orientationDescription(shouldRespectImageOrientation());
429 #if ENABLE(CSS_IMAGE_ORIENTATION)
430 orientationDescription.setImageOrientationEnum(style().imageOrientation());
432 context.drawImage(*image, snapRectToDevicePixels(LayoutRect(paintOffset + imageOffset, imageSize), deviceScaleFactor), orientationDescription);
433 errorPictureDrawn = true;
436 if (!m_altText.isEmpty()) {
437 String text = document().displayStringModifiedByEncoding(m_altText);
438 context.setFillColor(style().visitedDependentColor(CSSPropertyColor));
439 const FontCascade& font = style().fontCascade();
440 const FontMetrics& fontMetrics = font.fontMetrics();
441 LayoutUnit ascent = fontMetrics.ascent();
442 LayoutPoint altTextOffset = paintOffset;
443 altTextOffset.move(leftBorder + leftPad + (paddingWidth / 2) - borderWidth, topBorder + topPad + ascent + (paddingHeight / 2) - borderWidth);
445 // Only draw the alt text if it'll fit within the content box,
446 // and only if it fits above the error image.
447 TextRun textRun = RenderBlock::constructTextRun(text, style());
448 LayoutUnit textWidth = font.width(textRun);
449 if (errorPictureDrawn) {
450 if (usableSize.width() >= textWidth && fontMetrics.height() <= imageOffset.height())
451 context.drawText(font, textRun, altTextOffset);
452 } else if (usableSize.width() >= textWidth && usableSize.height() >= fontMetrics.height())
453 context.drawText(font, textRun, altTextOffset);
459 if (contentSize.isEmpty())
462 RefPtr<Image> img = imageResource().image(flooredIntSize(contentSize));
463 if (!img || img->isNull()) {
464 if (paintInfo.phase == PaintPhaseForeground)
465 page().addRelevantUnpaintedObject(this, visualOverflowRect());
469 LayoutRect contentBoxRect = this->contentBoxRect();
470 contentBoxRect.moveBy(paintOffset);
471 LayoutRect replacedContentRect = this->replacedContentRect(intrinsicSize());
472 replacedContentRect.moveBy(paintOffset);
473 bool clip = !contentBoxRect.contains(replacedContentRect);
474 GraphicsContextStateSaver stateSaver(context, clip);
476 context.clip(contentBoxRect);
478 ImageDrawResult result = paintIntoRect(paintInfo, snapRectToDevicePixels(replacedContentRect, deviceScaleFactor));
480 if (cachedImage() && paintInfo.phase == PaintPhaseForeground) {
481 // For now, count images as unpainted if they are still progressively loading. We may want
482 // to refine this in the future to account for the portion of the image that has painted.
483 LayoutRect visibleRect = intersection(replacedContentRect, contentBoxRect);
484 if (cachedImage()->isLoading() || result == ImageDrawResult::DidRequestDecoding)
485 page().addRelevantUnpaintedObject(this, visibleRect);
487 page().addRelevantRepaintedObject(this, visibleRect);
491 void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
493 RenderReplaced::paint(paintInfo, paintOffset);
495 if (paintInfo.phase == PaintPhaseOutline)
496 paintAreaElementFocusRing(paintInfo, paintOffset);
499 void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
502 UNUSED_PARAM(paintInfo);
503 UNUSED_PARAM(paintOffset);
505 if (document().printing() || !frame().selection().isFocusedAndActive())
508 if (paintInfo.context().paintingDisabled() && !paintInfo.context().updatingControlTints())
511 Element* focusedElement = document().focusedElement();
512 if (!is<HTMLAreaElement>(focusedElement))
515 HTMLAreaElement& areaElement = downcast<HTMLAreaElement>(*focusedElement);
516 if (areaElement.imageElement() != element())
519 auto* areaElementStyle = areaElement.computedStyle();
520 if (!areaElementStyle)
523 float outlineWidth = areaElementStyle->outlineWidth();
527 // Even if the theme handles focus ring drawing for entire elements, it won't do it for
528 // an area within an image, so we don't call RenderTheme::supportsFocusRing here.
529 auto path = areaElement.computePathForFocusRing(size());
533 AffineTransform zoomTransform;
534 zoomTransform.scale(style().effectiveZoom());
535 path.transform(zoomTransform);
537 auto adjustedOffset = paintOffset;
538 adjustedOffset.moveBy(location());
539 path.translate(toFloatSize(adjustedOffset));
543 paintInfo.context().drawFocusRing(path, page().focusController().timeSinceFocusWasSet(), needsRepaint);
545 page().focusController().setFocusedElementNeedsRepaint();
547 paintInfo.context().drawFocusRing(path, outlineWidth, areaElementStyle->outlineOffset(), areaElementStyle->visitedDependentColor(CSSPropertyOutlineColor));
552 void RenderImage::areaElementFocusChanged(HTMLAreaElement* element)
554 ASSERT_UNUSED(element, element->imageElement() == this->element());
556 // It would be more efficient to only repaint the focus ring rectangle
557 // for the passed-in area element. That would require adding functions
558 // to the area element class.
562 ImageDrawResult RenderImage::paintIntoRect(PaintInfo& paintInfo, const FloatRect& rect)
564 if (!imageResource().cachedImage() || imageResource().errorOccurred() || rect.width() <= 0 || rect.height() <= 0)
565 return ImageDrawResult::DidNothing;
567 RefPtr<Image> img = imageResource().image(flooredIntSize(rect.size()));
568 if (!img || img->isNull())
569 return ImageDrawResult::DidNothing;
571 HTMLImageElement* imageElement = is<HTMLImageElement>(element()) ? downcast<HTMLImageElement>(element()) : nullptr;
572 CompositeOperator compositeOperator = imageElement ? imageElement->compositeOperator() : CompositeSourceOver;
574 // FIXME: Document when image != img.get().
575 Image* image = imageResource().image().get();
576 InterpolationQuality interpolation = image ? chooseInterpolationQuality(paintInfo.context(), *image, image, LayoutSize(rect.size())) : InterpolationDefault;
579 if (is<PDFDocumentImage>(image))
580 downcast<PDFDocumentImage>(*image).setPdfImageCachingPolicy(settings().pdfImageCachingPolicy());
583 if (is<BitmapImage>(image))
584 downcast<BitmapImage>(*image).updateFromSettings(settings());
586 ImageOrientationDescription orientationDescription(shouldRespectImageOrientation(), style().imageOrientation());
587 auto decodingMode = decodingModeForImageDraw(*image, paintInfo);
588 auto drawResult = paintInfo.context().drawImage(*img, rect, ImagePaintingOptions(compositeOperator, BlendModeNormal, decodingMode, orientationDescription, interpolation));
589 if (drawResult == ImageDrawResult::DidRequestDecoding)
590 imageResource().cachedImage()->addPendingImageDrawingClient(*this);
594 bool RenderImage::boxShadowShouldBeAppliedToBackground(const LayoutPoint& paintOffset, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox*) const
596 if (!RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(paintOffset, bleedAvoidance))
599 return !const_cast<RenderImage*>(this)->backgroundIsKnownToBeObscured(paintOffset);
602 bool RenderImage::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
604 UNUSED_PARAM(maxDepthToTest);
605 if (!imageResource().cachedImage() || imageResource().errorOccurred())
607 if (cachedImage() && !cachedImage()->isLoaded())
609 if (!contentBoxRect().contains(localRect))
611 EFillBox backgroundClip = style().backgroundClip();
612 // Background paints under borders.
613 if (backgroundClip == BorderFillBox && style().hasBorder() && !borderObscuresBackground())
615 // Background shows in padding area.
616 if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style().hasPadding())
618 // Object-fit may leave parts of the content box empty.
619 ObjectFit objectFit = style().objectFit();
620 if (objectFit != ObjectFitFill && objectFit != ObjectFitCover)
623 LengthPoint objectPosition = style().objectPosition();
624 if (objectPosition != RenderStyle::initialObjectPosition())
627 // Check for image with alpha.
628 return cachedImage() && cachedImage()->currentFrameKnownToBeOpaque(this);
631 bool RenderImage::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
633 if (!hasBackground())
636 LayoutRect paintedExtent;
637 if (!getBackgroundPaintedExtent(paintOffset, paintedExtent))
639 return foregroundIsKnownToBeOpaqueInRect(paintedExtent, 0);
642 LayoutUnit RenderImage::minimumReplacedHeight() const
644 return imageResource().errorOccurred() ? intrinsicSize().height() : LayoutUnit();
647 HTMLMapElement* RenderImage::imageMap() const
649 HTMLImageElement* image = is<HTMLImageElement>(element()) ? downcast<HTMLImageElement>(element()) : nullptr;
650 return image ? image->treeScope().getImageMap(image->attributeWithoutSynchronization(usemapAttr)) : nullptr;
653 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
655 HitTestResult tempResult(result.hitTestLocation());
656 bool inside = RenderReplaced::nodeAtPoint(request, tempResult, locationInContainer, accumulatedOffset, hitTestAction);
658 if (tempResult.innerNode() && element()) {
659 if (HTMLMapElement* map = imageMap()) {
660 LayoutRect contentBox = contentBoxRect();
661 float scaleFactor = 1 / style().effectiveZoom();
662 LayoutPoint mapLocation = locationInContainer.point() - toLayoutSize(accumulatedOffset) - locationOffset() - toLayoutSize(contentBox.location());
663 mapLocation.scale(scaleFactor);
665 if (map->mapMouseEvent(mapLocation, contentBox.size(), tempResult))
666 tempResult.setInnerNonSharedNode(element());
670 if (!inside && request.resultIsElementList())
671 result.append(tempResult, request);
677 void RenderImage::updateAltText()
682 if (is<HTMLInputElement>(*element()))
683 m_altText = downcast<HTMLInputElement>(*element()).altText();
684 else if (is<HTMLImageElement>(*element()))
685 m_altText = downcast<HTMLImageElement>(*element()).altText();
688 bool RenderImage::canHaveChildren() const
690 #if !ENABLE(SERVICE_CONTROLS)
693 return m_hasShadowControls;
697 void RenderImage::layout()
699 StackStats::LayoutCheckPoint layoutCheckPoint;
701 LayoutSize oldSize = contentBoxRect().size();
702 RenderReplaced::layout();
704 updateInnerContentRect();
706 if (m_hasShadowControls)
707 layoutShadowControls(oldSize);
710 void RenderImage::layoutShadowControls(const LayoutSize& oldSize)
712 // We expect a single containing box under the UA shadow root.
713 ASSERT(firstChild() == lastChild());
715 auto* controlsRenderer = downcast<RenderBox>(firstChild());
716 if (!controlsRenderer)
719 bool controlsNeedLayout = controlsRenderer->needsLayout();
720 // If the region chain has changed we also need to relayout the controls to update the region box info.
721 // FIXME: We can do better once we compute region box info for RenderReplaced, not only for RenderBlock.
722 const RenderFlowThread* flowThread = flowThreadContainingBlock();
723 if (flowThread && !controlsNeedLayout) {
724 if (flowThread->pageLogicalSizeChanged())
725 controlsNeedLayout = true;
728 LayoutSize newSize = contentBoxRect().size();
729 if (newSize == oldSize && !controlsNeedLayout)
732 // When calling layout() on a child node, a parent must either push a LayoutStateMaintainter, or
733 // instantiate LayoutStateDisabler. Since using a LayoutStateMaintainer is slightly more efficient,
734 // and this method might be called many times per second during video playback, use a LayoutStateMaintainer:
735 LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
737 if (shadowControlsNeedCustomLayoutMetrics()) {
738 controlsRenderer->setLocation(LayoutPoint(borderLeft(), borderTop()) + LayoutSize(paddingLeft(), paddingTop()));
739 controlsRenderer->mutableStyle().setHeight(Length(newSize.height(), Fixed));
740 controlsRenderer->mutableStyle().setWidth(Length(newSize.width(), Fixed));
743 controlsRenderer->setNeedsLayout(MarkOnlyThis);
744 controlsRenderer->layout();
745 clearChildNeedsLayout();
750 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
752 RenderReplaced::computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
754 // Our intrinsicSize is empty if we're rendering generated images with relative width/height. Figure out the right intrinsic size to use.
755 if (intrinsicSize.isEmpty() && (imageResource().imageHasRelativeWidth() || imageResource().imageHasRelativeHeight())) {
756 RenderObject* containingBlock = isOutOfFlowPositioned() ? container() : this->containingBlock();
757 if (is<RenderBox>(*containingBlock)) {
758 auto& box = downcast<RenderBox>(*containingBlock);
759 intrinsicSize.setWidth(box.availableLogicalWidth());
760 intrinsicSize.setHeight(box.availableLogicalHeight(IncludeMarginBorderPadding));
763 // Don't compute an intrinsic ratio to preserve historical WebKit behavior if we're painting alt text and/or a broken image.
764 if (imageResource().errorOccurred()) {
770 bool RenderImage::needsPreferredWidthsRecalculation() const
772 if (RenderReplaced::needsPreferredWidthsRecalculation())
774 return embeddedContentBox();
777 RenderBox* RenderImage::embeddedContentBox() const
779 CachedImage* cachedImage = this->cachedImage();
780 if (cachedImage && is<SVGImage>(cachedImage->image()))
781 return downcast<SVGImage>(*cachedImage->image()).embeddedContentBox();
786 } // namespace WebCore