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 "core/rendering/RenderImage.h"
31 #include "core/HTMLNames.h"
32 #include "core/editing/FrameSelection.h"
33 #include "core/fetch/ImageResource.h"
34 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
35 #include "core/fetch/ResourceLoader.h"
36 #include "core/frame/LocalFrame.h"
37 #include "core/html/HTMLAreaElement.h"
38 #include "core/html/HTMLImageElement.h"
39 #include "core/html/HTMLInputElement.h"
40 #include "core/html/HTMLMapElement.h"
41 #include "core/inspector/InspectorInstrumentation.h"
42 #include "core/inspector/InspectorTraceEvents.h"
43 #include "core/rendering/HitTestResult.h"
44 #include "core/rendering/PaintInfo.h"
45 #include "core/rendering/RenderView.h"
46 #include "core/rendering/TextRunConstructor.h"
47 #include "core/svg/graphics/SVGImage.h"
48 #include "platform/fonts/Font.h"
49 #include "platform/fonts/FontCache.h"
50 #include "platform/graphics/GraphicsContext.h"
51 #include "platform/graphics/GraphicsContextStateSaver.h"
55 float deviceScaleFactor(LocalFrame*);
57 using namespace HTMLNames;
59 RenderImage::RenderImage(Element* element)
60 : RenderReplaced(element, IntSize())
61 , m_didIncrementVisuallyNonEmptyPixelCount(false)
62 , m_isGeneratedContent(false)
63 , m_imageDevicePixelRatio(1.0f)
66 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
69 RenderImage* RenderImage::createAnonymous(Document* document)
71 RenderImage* image = new RenderImage(0);
72 image->setDocumentForAnonymous(document);
76 RenderImage::~RenderImage()
80 void RenderImage::destroy()
82 ASSERT(m_imageResource);
83 m_imageResource->shutdown();
84 RenderReplaced::destroy();
87 void RenderImage::setImageResource(PassOwnPtr<RenderImageResource> imageResource)
89 ASSERT(!m_imageResource);
90 m_imageResource = imageResource;
91 m_imageResource->initialize(this);
94 // If we'll be displaying either alt text or an image, add some padding.
95 static const unsigned short paddingWidth = 4;
96 static const unsigned short paddingHeight = 4;
98 // Alt text is restricted to this maximum size, in pixels. These are
99 // signed integers because they are compared with other signed values.
100 static const float maxAltTextWidth = 1024;
101 static const int maxAltTextHeight = 256;
103 IntSize RenderImage::imageSizeForError(ImageResource* newImage) const
105 ASSERT_ARG(newImage, newImage);
106 ASSERT_ARG(newImage, newImage->imageForRenderer(this));
109 if (newImage->willPaintBrokenImage()) {
110 float deviceScaleFactor = blink::deviceScaleFactor(frame());
111 pair<Image*, float> brokenImageAndImageScaleFactor = ImageResource::brokenImage(deviceScaleFactor);
112 imageSize = brokenImageAndImageScaleFactor.first->size();
113 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
115 imageSize = newImage->imageForRenderer(this)->size();
117 // imageSize() returns 0 for the error image. We need the true size of the
118 // error image, so we have to get it by grabbing image() directly.
119 return IntSize(paddingWidth + imageSize.width() * style()->effectiveZoom(), paddingHeight + imageSize.height() * style()->effectiveZoom());
122 // Sets the image height and width to fit the alt text. Returns true if the
123 // image size changed.
124 bool RenderImage::setImageSizeForAltText(ImageResource* newImage /* = 0 */)
127 if (newImage && newImage->imageForRenderer(this))
128 imageSize = imageSizeForError(newImage);
129 else if (!m_altText.isEmpty() || newImage) {
130 // If we'll be displaying either text or an image, add a little padding.
131 imageSize = IntSize(paddingWidth, paddingHeight);
134 // we have an alt and the user meant it (its not a text we invented)
135 if (!m_altText.isEmpty()) {
136 FontCachePurgePreventer fontCachePurgePreventer;
138 const Font& font = style()->font();
139 IntSize paddedTextSize(paddingWidth + std::min(ceilf(font.width(constructTextRun(this, font, m_altText, style()))), maxAltTextWidth), paddingHeight + std::min(font.fontMetrics().height(), maxAltTextHeight));
140 imageSize = imageSize.expandedTo(paddedTextSize);
143 if (imageSize == intrinsicSize())
146 setIntrinsicSize(imageSize);
150 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
152 if (documentBeingDestroyed())
155 if (hasBoxDecorationBackground() || hasMask() || hasShapeOutside())
156 RenderReplaced::imageChanged(newImage, rect);
158 if (!m_imageResource)
161 if (newImage != m_imageResource->imagePtr())
164 // Per the spec, we let the server-sent header override srcset/other sources of dpr.
165 // https://github.com/igrigorik/http-client-hints/blob/master/draft-grigorik-http-client-hints-01.txt#L255
166 if (m_imageResource->cachedImage() && m_imageResource->cachedImage()->hasDevicePixelRatioHeaderValue())
167 m_imageDevicePixelRatio = 1 / m_imageResource->cachedImage()->devicePixelRatioHeaderValue();
169 if (!m_didIncrementVisuallyNonEmptyPixelCount) {
170 // At a zoom level of 1 the image is guaranteed to have an integer size.
171 view()->frameView()->incrementVisuallyNonEmptyPixelCount(flooredIntSize(m_imageResource->imageSize(1.0f)));
172 m_didIncrementVisuallyNonEmptyPixelCount = true;
175 bool imageSizeChanged = false;
177 // Set image dimensions, taking into account the size of the alt text.
178 if (m_imageResource->errorOccurred() || !newImage)
179 imageSizeChanged = setImageSizeForAltText(m_imageResource->cachedImage());
181 repaintOrMarkForLayout(imageSizeChanged, rect);
184 void RenderImage::updateIntrinsicSizeIfNeeded(const LayoutSize& newSize)
186 if (m_imageResource->errorOccurred() || !m_imageResource->hasImage())
188 setIntrinsicSize(newSize);
191 void RenderImage::updateInnerContentRect()
193 // Propagate container size to the image resource.
194 LayoutRect containerRect = replacedContentRect();
195 IntSize containerSize(containerRect.width(), containerRect.height());
196 if (!containerSize.isEmpty())
197 m_imageResource->setContainerSizeForRenderer(containerSize);
200 void RenderImage::repaintOrMarkForLayout(bool imageSizeChangedToAccomodateAltText, const IntRect* rect)
202 LayoutSize oldIntrinsicSize = intrinsicSize();
203 LayoutSize newIntrinsicSize = m_imageResource->intrinsicSize(style()->effectiveZoom());
204 updateIntrinsicSizeIfNeeded(newIntrinsicSize);
206 // In the case of generated image content using :before/:after/content, we might not be
207 // in the render tree yet. In that case, we just need to update our intrinsic size.
208 // layout() will be called after we are inserted in the tree which will take care of
209 // what we are doing here.
210 if (!containingBlock())
213 bool imageSourceHasChangedSize = oldIntrinsicSize != newIntrinsicSize || imageSizeChangedToAccomodateAltText;
214 if (imageSourceHasChangedSize)
215 setPreferredLogicalWidthsDirty();
217 // If the actual area occupied by the image has changed and it is not constrained by style then a layout is required.
218 bool imageSizeIsConstrained = style()->logicalWidth().isSpecified() && style()->logicalHeight().isSpecified();
220 // FIXME: We only need to recompute the containing block's preferred size if the containing block's size
221 // depends on the image's size (i.e., the container uses shrink-to-fit sizing).
222 // There's no easy way to detect that shrink-to-fit is needed, always force a layout.
223 bool containingBlockNeedsToRecomputePreferredSize = style()->logicalWidth().isPercent() || style()->logicalMaxWidth().isPercent() || style()->logicalMinWidth().isPercent();
225 if (imageSourceHasChangedSize && (!imageSizeIsConstrained || containingBlockNeedsToRecomputePreferredSize)) {
226 setNeedsLayoutAndFullPaintInvalidation();
230 // The image hasn't changed in size or its style constrains its size, so a repaint will suffice.
231 if (everHadLayout() && !selfNeedsLayout()) {
232 // The inner content rectangle is calculated during layout, but may need an update now
233 // (unless the box has already been scheduled for layout). In order to calculate it, we
234 // may need values from the containing block, though, so make sure that we're not too
235 // early. It may be that layout hasn't even taken place once yet.
236 updateInnerContentRect();
239 LayoutRect repaintRect;
241 // The image changed rect is in source image coordinates (without zoom),
242 // so map from the bounds of the image to the contentsBox.
243 const LayoutSize imageSizeWithoutZoom = m_imageResource->imageSize(1 / style()->effectiveZoom());
244 repaintRect = enclosingIntRect(mapRect(*rect, FloatRect(FloatPoint(), imageSizeWithoutZoom), contentBoxRect()));
245 // Guard against too-large changed rects.
246 repaintRect.intersect(contentBoxRect());
248 repaintRect = contentBoxRect();
252 // FIXME: We should not be allowing repaint during layout. crbug.com/339584
253 AllowPaintInvalidationScope scoper(frameView());
254 invalidatePaintRectangle(repaintRect);
257 // Tell any potential compositing layers that the image needs updating.
258 contentChanged(ImageChanged);
261 void RenderImage::notifyFinished(Resource* newImage)
263 if (!m_imageResource)
266 if (documentBeingDestroyed())
269 invalidateBackgroundObscurationStatus();
271 if (newImage == m_imageResource->cachedImage()) {
272 // tell any potential compositing layers
273 // that the image is done and they can reference it directly.
274 contentChanged(ImageChanged);
278 void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
280 LayoutUnit cWidth = contentWidth();
281 LayoutUnit cHeight = contentHeight();
282 LayoutUnit leftBorder = borderLeft();
283 LayoutUnit topBorder = borderTop();
284 LayoutUnit leftPad = paddingLeft();
285 LayoutUnit topPad = paddingTop();
287 GraphicsContext* context = paintInfo.context;
289 if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
290 if (paintInfo.phase == PaintPhaseSelection)
293 if (cWidth > 2 && cHeight > 2) {
294 const int borderWidth = 1;
296 // Draw an outline rect where the image should be.
297 context->setStrokeStyle(SolidStroke);
298 context->setStrokeColor(Color::lightGray);
299 context->setFillColor(Color::transparent);
300 context->drawRect(pixelSnappedIntRect(LayoutRect(paintOffset.x() + leftBorder + leftPad, paintOffset.y() + topBorder + topPad, cWidth, cHeight)));
302 bool errorPictureDrawn = false;
303 LayoutSize imageOffset;
304 // When calculating the usable dimensions, exclude the pixels of
305 // the ouline rect so the error image/alt text doesn't draw on it.
306 LayoutUnit usableWidth = cWidth - 2 * borderWidth;
307 LayoutUnit usableHeight = cHeight - 2 * borderWidth;
309 RefPtr<Image> image = m_imageResource->image();
311 if (m_imageResource->errorOccurred() && !image->isNull() && usableWidth >= image->width() && usableHeight >= image->height()) {
312 float deviceScaleFactor = blink::deviceScaleFactor(frame());
313 // Call brokenImage() explicitly to ensure we get the broken image icon at the appropriate resolution.
314 pair<Image*, float> brokenImageAndImageScaleFactor = ImageResource::brokenImage(deviceScaleFactor);
315 image = brokenImageAndImageScaleFactor.first;
316 IntSize imageSize = image->size();
317 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
318 // Center the error image, accounting for border and padding.
319 LayoutUnit centerX = (usableWidth - imageSize.width()) / 2;
322 LayoutUnit centerY = (usableHeight - imageSize.height()) / 2;
325 imageOffset = LayoutSize(leftBorder + leftPad + centerX + borderWidth, topBorder + topPad + centerY + borderWidth);
326 context->drawImage(image.get(), pixelSnappedIntRect(LayoutRect(paintOffset + imageOffset, imageSize)), CompositeSourceOver, shouldRespectImageOrientation());
327 errorPictureDrawn = true;
330 if (!m_altText.isEmpty()) {
331 const Font& font = style()->font();
332 const FontMetrics& fontMetrics = font.fontMetrics();
333 LayoutUnit ascent = fontMetrics.ascent();
334 LayoutPoint textRectOrigin = paintOffset;
335 textRectOrigin.move(leftBorder + leftPad + (paddingWidth / 2) - borderWidth, topBorder + topPad + (paddingHeight / 2) - borderWidth);
336 LayoutPoint textOrigin(textRectOrigin.x(), textRectOrigin.y() + ascent);
338 // Only draw the alt text if it'll fit within the content box,
339 // and only if it fits above the error image.
340 TextRun textRun = constructTextRun(this, font, m_altText, style(), TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, DefaultTextRunFlags | RespectDirection);
341 float textWidth = font.width(textRun);
342 TextRunPaintInfo textRunPaintInfo(textRun);
343 textRunPaintInfo.bounds = FloatRect(textRectOrigin, FloatSize(textWidth, fontMetrics.height()));
344 context->setFillColor(resolveColor(CSSPropertyColor));
345 if (textRun.direction() == RTL) {
346 int availableWidth = cWidth - static_cast<int>(paddingWidth);
347 textOrigin.move(availableWidth - ceilf(textWidth), 0);
349 if (errorPictureDrawn) {
350 if (usableWidth >= textWidth && fontMetrics.height() <= imageOffset.height())
351 context->drawBidiText(font, textRunPaintInfo, textOrigin);
352 } else if (usableWidth >= textWidth && usableHeight >= fontMetrics.height()) {
353 context->drawBidiText(font, textRunPaintInfo, textOrigin);
357 } else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
358 RefPtr<Image> img = m_imageResource->image(cWidth, cHeight);
359 if (!img || img->isNull())
362 LayoutRect contentRect = contentBoxRect();
363 contentRect.moveBy(paintOffset);
364 LayoutRect paintRect = replacedContentRect();
365 paintRect.moveBy(paintOffset);
366 bool clip = !contentRect.contains(paintRect);
369 context->clip(contentRect);
372 paintIntoRect(context, paintRect);
379 void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
381 RenderReplaced::paint(paintInfo, paintOffset);
383 if (paintInfo.phase == PaintPhaseOutline)
384 paintAreaElementFocusRing(paintInfo);
387 void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo)
389 Document& document = this->document();
391 if (document.printing() || !document.frame()->selection().isFocusedAndActive())
394 Element* focusedElement = document.focusedElement();
395 if (!isHTMLAreaElement(focusedElement))
398 HTMLAreaElement& areaElement = toHTMLAreaElement(*focusedElement);
399 if (areaElement.imageElement() != node())
402 // Even if the theme handles focus ring drawing for entire elements, it won't do it for
403 // an area within an image, so we don't call RenderTheme::supportsFocusRing here.
405 Path path = areaElement.computePath(this);
409 RenderStyle* areaElementStyle = areaElement.computedStyle();
410 unsigned short outlineWidth = areaElementStyle->outlineWidth();
414 // FIXME: Clip path instead of context when Skia pathops is ready.
415 // https://crbug.com/251206
416 GraphicsContextStateSaver savedContext(*paintInfo.context);
417 paintInfo.context->clip(absoluteContentBox());
418 paintInfo.context->drawFocusRing(path, outlineWidth,
419 areaElementStyle->outlineOffset(),
420 resolveColor(areaElementStyle, CSSPropertyOutlineColor));
423 void RenderImage::areaElementFocusChanged(HTMLAreaElement* areaElement)
425 ASSERT(areaElement->imageElement() == node());
427 Path path = areaElement->computePath(this);
431 RenderStyle* areaElementStyle = areaElement->computedStyle();
432 unsigned short outlineWidth = areaElementStyle->outlineWidth();
434 IntRect repaintRect = enclosingIntRect(path.boundingRect());
435 repaintRect.moveBy(-absoluteContentBox().location());
436 repaintRect.inflate(outlineWidth);
438 invalidatePaintRectangle(repaintRect);
441 void RenderImage::paintIntoRect(GraphicsContext* context, const LayoutRect& rect)
443 IntRect alignedRect = pixelSnappedIntRect(rect);
444 if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || alignedRect.width() <= 0 || alignedRect.height() <= 0)
447 RefPtr<Image> img = m_imageResource->image(alignedRect.width(), alignedRect.height());
448 if (!img || img->isNull())
451 HTMLImageElement* imageElt = isHTMLImageElement(node()) ? toHTMLImageElement(node()) : 0;
452 CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
453 Image* image = m_imageResource->image().get();
454 InterpolationQuality interpolationQuality = chooseInterpolationQuality(context, image, image, alignedRect.size());
456 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage", "data", InspectorPaintImageEvent::data(*this));
457 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
458 InspectorInstrumentation::willPaintImage(this);
459 InterpolationQuality previousInterpolationQuality = context->imageInterpolationQuality();
460 context->setImageInterpolationQuality(interpolationQuality);
461 context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), alignedRect, compositeOperator, shouldRespectImageOrientation());
462 context->setImageInterpolationQuality(previousInterpolationQuality);
463 InspectorInstrumentation::didPaintImage(this);
466 bool RenderImage::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox*) const
468 if (!RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(bleedAvoidance))
471 return !const_cast<RenderImage*>(this)->boxDecorationBackgroundIsKnownToBeObscured();
474 bool RenderImage::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned) const
476 if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
478 if (m_imageResource->cachedImage() && !m_imageResource->cachedImage()->isLoaded())
480 if (!contentBoxRect().contains(localRect))
482 EFillBox backgroundClip = style()->backgroundClip();
483 // Background paints under borders.
484 if (backgroundClip == BorderFillBox && style()->hasBorder() && !borderObscuresBackground())
486 // Background shows in padding area.
487 if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style()->hasPadding())
489 // Object-position may leave parts of the content box empty, regardless of the value of object-fit.
490 if (style()->objectPosition() != RenderStyle::initialObjectPosition())
492 // Object-fit may leave parts of the content box empty.
493 ObjectFit objectFit = style()->objectFit();
494 if (objectFit != ObjectFitFill && objectFit != ObjectFitCover)
496 // Check for image with alpha.
497 return m_imageResource->cachedImage() && m_imageResource->cachedImage()->currentFrameKnownToBeOpaque(this);
500 bool RenderImage::computeBackgroundIsKnownToBeObscured()
502 if (!hasBackground())
505 LayoutRect paintedExtent;
506 if (!getBackgroundPaintedExtent(paintedExtent))
508 return foregroundIsKnownToBeOpaqueInRect(paintedExtent, 0);
511 LayoutUnit RenderImage::minimumReplacedHeight() const
513 return m_imageResource->errorOccurred() ? intrinsicSize().height() : LayoutUnit();
516 HTMLMapElement* RenderImage::imageMap() const
518 HTMLImageElement* i = isHTMLImageElement(node()) ? toHTMLImageElement(node()) : 0;
519 return i ? i->treeScope().getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
522 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
524 HitTestResult tempResult(result.hitTestLocation());
525 bool inside = RenderReplaced::nodeAtPoint(request, tempResult, locationInContainer, accumulatedOffset, hitTestAction);
527 if (tempResult.innerNode() && node()) {
528 if (HTMLMapElement* map = imageMap()) {
529 LayoutRect contentBox = contentBoxRect();
530 float scaleFactor = 1 / style()->effectiveZoom();
531 LayoutPoint mapLocation = locationInContainer.point() - toLayoutSize(accumulatedOffset) - locationOffset() - toLayoutSize(contentBox.location());
532 mapLocation.scale(scaleFactor, scaleFactor);
534 if (map->mapMouseEvent(mapLocation, contentBox.size(), tempResult))
535 tempResult.setInnerNonSharedNode(node());
539 if (!inside && result.isRectBasedTest())
540 result.append(tempResult);
546 void RenderImage::updateAltText()
551 if (isHTMLInputElement(*node()))
552 m_altText = toHTMLInputElement(node())->altText();
553 else if (isHTMLImageElement(*node()))
554 m_altText = toHTMLImageElement(node())->altText();
557 void RenderImage::layout()
559 LayoutRect oldContentRect = replacedContentRect();
560 RenderReplaced::layout();
561 if (replacedContentRect() != oldContentRect)
562 setShouldDoFullPaintInvalidation(true);
563 updateInnerContentRect();
566 bool RenderImage::updateImageLoadingPriorities()
568 if (!m_imageResource || !m_imageResource->cachedImage() || m_imageResource->cachedImage()->isLoaded())
571 LayoutRect viewBounds = viewRect();
572 LayoutRect objectBounds = absoluteContentBox();
574 // The object bounds might be empty right now, so intersects will fail since it doesn't deal
575 // with empty rects. Use LayoutRect::contains in that case.
577 if (!objectBounds.isEmpty())
578 isVisible = viewBounds.intersects(objectBounds);
580 isVisible = viewBounds.contains(objectBounds);
582 ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
583 ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
585 LayoutRect screenArea;
586 if (!objectBounds.isEmpty()) {
587 screenArea = viewBounds;
588 screenArea.intersect(objectBounds);
591 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(m_imageResource->cachedImage(), status, screenArea);
596 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
598 RenderReplaced::computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
600 // Our intrinsicSize is empty if we're rendering generated images with relative width/height. Figure out the right intrinsic size to use.
601 if (intrinsicSize.isEmpty() && (m_imageResource->imageHasRelativeWidth() || m_imageResource->imageHasRelativeHeight())) {
602 RenderObject* containingBlock = isOutOfFlowPositioned() ? container() : this->containingBlock();
603 if (containingBlock->isBox()) {
604 RenderBox* box = toRenderBox(containingBlock);
605 intrinsicSize.setWidth(box->availableLogicalWidth().toFloat());
606 intrinsicSize.setHeight(box->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
609 // Don't compute an intrinsic ratio to preserve historical WebKit behavior if we're painting alt text and/or a broken image.
610 // Video is excluded from this behavior because video elements have a default aspect ratio that a failed poster image load should not override.
611 if (m_imageResource && m_imageResource->errorOccurred() && !isVideo()) {
617 bool RenderImage::needsPreferredWidthsRecalculation() const
619 if (RenderReplaced::needsPreferredWidthsRecalculation())
621 return embeddedContentBox();
624 RenderBox* RenderImage::embeddedContentBox() const
626 if (!m_imageResource)
629 ImageResource* cachedImage = m_imageResource->cachedImage();
630 if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
631 return toSVGImage(cachedImage->image())->embeddedContentBox();