Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderImage.cpp
1 /*
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.
10  *
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.
15  *
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.
20  *
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.
25  *
26  */
27
28 #include "config.h"
29 #include "core/rendering/RenderImage.h"
30
31 #include "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/rendering/HitTestResult.h"
43 #include "core/rendering/PaintInfo.h"
44 #include "core/rendering/RenderView.h"
45 #include "core/svg/graphics/SVGImage.h"
46 #include "platform/fonts/Font.h"
47 #include "platform/fonts/FontCache.h"
48 #include "platform/graphics/GraphicsContext.h"
49 #include "platform/graphics/GraphicsContextStateSaver.h"
50
51 using namespace std;
52
53 namespace WebCore {
54
55 using namespace HTMLNames;
56
57 RenderImage::RenderImage(Element* element)
58     : RenderReplaced(element, IntSize())
59     , m_didIncrementVisuallyNonEmptyPixelCount(false)
60     , m_isGeneratedContent(false)
61     , m_imageDevicePixelRatio(1.0f)
62 {
63     updateAltText();
64     ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
65 }
66
67 RenderImage* RenderImage::createAnonymous(Document* document)
68 {
69     RenderImage* image = new RenderImage(0);
70     image->setDocumentForAnonymous(document);
71     return image;
72 }
73
74 RenderImage::~RenderImage()
75 {
76     ASSERT(m_imageResource);
77     m_imageResource->shutdown();
78 }
79
80 void RenderImage::setImageResource(PassOwnPtr<RenderImageResource> imageResource)
81 {
82     ASSERT(!m_imageResource);
83     m_imageResource = imageResource;
84     m_imageResource->initialize(this);
85 }
86
87 // If we'll be displaying either alt text or an image, add some padding.
88 static const unsigned short paddingWidth = 4;
89 static const unsigned short paddingHeight = 4;
90
91 // Alt text is restricted to this maximum size, in pixels.  These are
92 // signed integers because they are compared with other signed values.
93 static const float maxAltTextWidth = 1024;
94 static const int maxAltTextHeight = 256;
95
96 IntSize RenderImage::imageSizeForError(ImageResource* newImage) const
97 {
98     ASSERT_ARG(newImage, newImage);
99     ASSERT_ARG(newImage, newImage->imageForRenderer(this));
100
101     IntSize imageSize;
102     if (newImage->willPaintBrokenImage()) {
103         float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
104         pair<Image*, float> brokenImageAndImageScaleFactor = ImageResource::brokenImage(deviceScaleFactor);
105         imageSize = brokenImageAndImageScaleFactor.first->size();
106         imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
107     } else
108         imageSize = newImage->imageForRenderer(this)->size();
109
110     // imageSize() returns 0 for the error image. We need the true size of the
111     // error image, so we have to get it by grabbing image() directly.
112     return IntSize(paddingWidth + imageSize.width() * style()->effectiveZoom(), paddingHeight + imageSize.height() * style()->effectiveZoom());
113 }
114
115 // Sets the image height and width to fit the alt text.  Returns true if the
116 // image size changed.
117 bool RenderImage::setImageSizeForAltText(ImageResource* newImage /* = 0 */)
118 {
119     IntSize imageSize;
120     if (newImage && newImage->imageForRenderer(this))
121         imageSize = imageSizeForError(newImage);
122     else if (!m_altText.isEmpty() || newImage) {
123         // If we'll be displaying either text or an image, add a little padding.
124         imageSize = IntSize(paddingWidth, paddingHeight);
125     }
126
127     // we have an alt and the user meant it (its not a text we invented)
128     if (!m_altText.isEmpty()) {
129         FontCachePurgePreventer fontCachePurgePreventer;
130
131         const Font& font = style()->font();
132         IntSize paddedTextSize(paddingWidth + min(ceilf(font.width(RenderBlockFlow::constructTextRun(this, font, m_altText, style()))), maxAltTextWidth), paddingHeight + min(font.fontMetrics().height(), maxAltTextHeight));
133         imageSize = imageSize.expandedTo(paddedTextSize);
134     }
135
136     if (imageSize == intrinsicSize())
137         return false;
138
139     setIntrinsicSize(imageSize);
140     return true;
141 }
142
143 void RenderImage::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
144 {
145     RenderReplaced::styleDidChange(diff, oldStyle);
146 }
147
148 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
149 {
150     if (documentBeingDestroyed())
151         return;
152
153     if (hasBoxDecorations() || hasMask() || hasShapeOutside())
154         RenderReplaced::imageChanged(newImage, rect);
155
156     if (!m_imageResource)
157         return;
158
159     if (newImage != m_imageResource->imagePtr())
160         return;
161
162     // Per the spec, we let the server-sent header override srcset/other sources of dpr.
163     // https://github.com/igrigorik/http-client-hints/blob/master/draft-grigorik-http-client-hints-01.txt#L255
164     if (m_imageResource->cachedImage() && m_imageResource->cachedImage()->hasDevicePixelRatioHeaderValue())
165         m_imageDevicePixelRatio = 1 / m_imageResource->cachedImage()->devicePixelRatioHeaderValue();
166
167     if (!m_didIncrementVisuallyNonEmptyPixelCount) {
168         // At a zoom level of 1 the image is guaranteed to have an integer size.
169         view()->frameView()->incrementVisuallyNonEmptyPixelCount(flooredIntSize(m_imageResource->imageSize(1.0f)));
170         m_didIncrementVisuallyNonEmptyPixelCount = true;
171     }
172
173     bool imageSizeChanged = false;
174
175     // Set image dimensions, taking into account the size of the alt text.
176     if (m_imageResource->errorOccurred() || !newImage)
177         imageSizeChanged = setImageSizeForAltText(m_imageResource->cachedImage());
178
179     repaintOrMarkForLayout(imageSizeChanged, rect);
180 }
181
182 void RenderImage::updateIntrinsicSizeIfNeeded(const LayoutSize& newSize)
183 {
184     if (m_imageResource->errorOccurred() || !m_imageResource->hasImage())
185         return;
186     setIntrinsicSize(newSize);
187 }
188
189 void RenderImage::updateInnerContentRect()
190 {
191     // Propagate container size to the image resource.
192     LayoutRect containerRect = replacedContentRect();
193     IntSize containerSize(containerRect.width(), containerRect.height());
194     if (!containerSize.isEmpty())
195         m_imageResource->setContainerSizeForRenderer(containerSize);
196 }
197
198 void RenderImage::repaintOrMarkForLayout(bool imageSizeChangedToAccomodateAltText, const IntRect* rect)
199 {
200     LayoutSize oldIntrinsicSize = intrinsicSize();
201     LayoutSize newIntrinsicSize = m_imageResource->intrinsicSize(style()->effectiveZoom());
202     updateIntrinsicSizeIfNeeded(newIntrinsicSize);
203
204     // In the case of generated image content using :before/:after/content, we might not be
205     // in the render tree yet. In that case, we just need to update our intrinsic size.
206     // layout() will be called after we are inserted in the tree which will take care of
207     // what we are doing here.
208     if (!containingBlock())
209         return;
210
211     bool imageSourceHasChangedSize = oldIntrinsicSize != newIntrinsicSize || imageSizeChangedToAccomodateAltText;
212     if (imageSourceHasChangedSize)
213         setPreferredLogicalWidthsDirty();
214
215     // If the actual area occupied by the image has changed and it is not constrained by style then a layout is required.
216     bool imageSizeIsConstrained = style()->logicalWidth().isSpecified() && style()->logicalHeight().isSpecified();
217     bool needsLayout = !imageSizeIsConstrained && imageSourceHasChangedSize;
218
219     // FIXME: We only need to recompute the containing block's preferred size if the containing block's size
220     // depends on the image's size (i.e., the container uses shrink-to-fit sizing).
221     // There's no easy way to detect that shrink-to-fit is needed, always force a layout.
222     bool containingBlockNeedsToRecomputePreferredSize =  style()->logicalWidth().isPercent() || style()->logicalMaxWidth().isPercent()  || style()->logicalMinWidth().isPercent();
223
224     if (needsLayout || containingBlockNeedsToRecomputePreferredSize) {
225         setNeedsLayout();
226         return;
227     }
228
229     // The image hasn't changed in size or its style constrains its size, so a repaint will suffice.
230     if (everHadLayout() && !selfNeedsLayout()) {
231         // The inner content rectangle is calculated during layout, but may need an update now
232         // (unless the box has already been scheduled for layout). In order to calculate it, we
233         // may need values from the containing block, though, so make sure that we're not too
234         // early. It may be that layout hasn't even taken place once yet.
235         updateInnerContentRect();
236     }
237
238     LayoutRect repaintRect;
239     if (rect) {
240         // The image changed rect is in source image coordinates (pre-zooming),
241         // so map from the bounds of the image to the contentsBox.
242         repaintRect = enclosingIntRect(mapRect(*rect, FloatRect(FloatPoint(), m_imageResource->imageSize(1.0f)), contentBoxRect()));
243         // Guard against too-large changed rects.
244         repaintRect.intersect(contentBoxRect());
245     } else {
246         repaintRect = contentBoxRect();
247     }
248
249     {
250         // FIXME: We should not be allowing repaint during layout. crbug.com/339584
251         AllowRepaintScope scoper(frameView());
252         repaintRectangle(repaintRect);
253     }
254
255     // Tell any potential compositing layers that the image needs updating.
256     contentChanged(ImageChanged);
257 }
258
259 void RenderImage::notifyFinished(Resource* newImage)
260 {
261     if (!m_imageResource)
262         return;
263
264     if (documentBeingDestroyed())
265         return;
266
267     invalidateBackgroundObscurationStatus();
268
269     if (newImage == m_imageResource->cachedImage()) {
270         // tell any potential compositing layers
271         // that the image is done and they can reference it directly.
272         contentChanged(ImageChanged);
273     }
274 }
275
276 void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
277 {
278     LayoutUnit cWidth = contentWidth();
279     LayoutUnit cHeight = contentHeight();
280     LayoutUnit leftBorder = borderLeft();
281     LayoutUnit topBorder = borderTop();
282     LayoutUnit leftPad = paddingLeft();
283     LayoutUnit topPad = paddingTop();
284
285     GraphicsContext* context = paintInfo.context;
286
287     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
288         if (paintInfo.phase == PaintPhaseSelection)
289             return;
290
291         if (cWidth > 2 && cHeight > 2) {
292             const int borderWidth = 1;
293
294             // Draw an outline rect where the image should be.
295             context->setStrokeStyle(SolidStroke);
296             context->setStrokeColor(Color::lightGray);
297             context->setFillColor(Color::transparent);
298             context->drawRect(pixelSnappedIntRect(LayoutRect(paintOffset.x() + leftBorder + leftPad, paintOffset.y() + topBorder + topPad, cWidth, cHeight)));
299
300             bool errorPictureDrawn = false;
301             LayoutSize imageOffset;
302             // When calculating the usable dimensions, exclude the pixels of
303             // the ouline rect so the error image/alt text doesn't draw on it.
304             LayoutUnit usableWidth = cWidth - 2 * borderWidth;
305             LayoutUnit usableHeight = cHeight - 2 * borderWidth;
306
307             RefPtr<Image> image = m_imageResource->image();
308
309             if (m_imageResource->errorOccurred() && !image->isNull() && usableWidth >= image->width() && usableHeight >= image->height()) {
310                 float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
311                 // Call brokenImage() explicitly to ensure we get the broken image icon at the appropriate resolution.
312                 pair<Image*, float> brokenImageAndImageScaleFactor = ImageResource::brokenImage(deviceScaleFactor);
313                 image = brokenImageAndImageScaleFactor.first;
314                 IntSize imageSize = image->size();
315                 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
316                 // Center the error image, accounting for border and padding.
317                 LayoutUnit centerX = (usableWidth - imageSize.width()) / 2;
318                 if (centerX < 0)
319                     centerX = 0;
320                 LayoutUnit centerY = (usableHeight - imageSize.height()) / 2;
321                 if (centerY < 0)
322                     centerY = 0;
323                 imageOffset = LayoutSize(leftBorder + leftPad + centerX + borderWidth, topBorder + topPad + centerY + borderWidth);
324                 context->drawImage(image.get(), pixelSnappedIntRect(LayoutRect(paintOffset + imageOffset, imageSize)), CompositeSourceOver, shouldRespectImageOrientation());
325                 errorPictureDrawn = true;
326             }
327
328             if (!m_altText.isEmpty()) {
329                 const Font& font = style()->font();
330                 const FontMetrics& fontMetrics = font.fontMetrics();
331                 LayoutUnit ascent = fontMetrics.ascent();
332                 LayoutPoint textRectOrigin = paintOffset;
333                 textRectOrigin.move(leftBorder + leftPad + (paddingWidth / 2) - borderWidth, topBorder + topPad + (paddingHeight / 2) - borderWidth);
334                 LayoutPoint textOrigin(textRectOrigin.x(), textRectOrigin.y() + ascent);
335
336                 // Only draw the alt text if it'll fit within the content box,
337                 // and only if it fits above the error image.
338                 TextRun textRun = RenderBlockFlow::constructTextRun(this, font, m_altText, style(), TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, DefaultTextRunFlags | RespectDirection);
339                 float textWidth = font.width(textRun);
340                 TextRunPaintInfo textRunPaintInfo(textRun);
341                 textRunPaintInfo.bounds = FloatRect(textRectOrigin, FloatSize(textWidth, fontMetrics.height()));
342                 context->setFillColor(resolveColor(CSSPropertyColor));
343                 if (textRun.direction() == RTL) {
344                     int availableWidth = cWidth - static_cast<int>(paddingWidth);
345                     textOrigin.move(availableWidth - ceilf(textWidth), 0);
346                 }
347                 if (errorPictureDrawn) {
348                     if (usableWidth >= textWidth && fontMetrics.height() <= imageOffset.height())
349                         context->drawBidiText(font, textRunPaintInfo, textOrigin);
350                 } else if (usableWidth >= textWidth && usableHeight >= fontMetrics.height()) {
351                     context->drawBidiText(font, textRunPaintInfo, textOrigin);
352                 }
353             }
354         }
355     } else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
356         RefPtr<Image> img = m_imageResource->image(cWidth, cHeight);
357         if (!img || img->isNull())
358             return;
359
360         LayoutRect contentRect = contentBoxRect();
361         contentRect.moveBy(paintOffset);
362         LayoutRect paintRect = replacedContentRect();
363         paintRect.moveBy(paintOffset);
364         bool clip = !contentRect.contains(paintRect);
365         if (clip) {
366             context->save();
367             context->clip(contentRect);
368         }
369
370         paintIntoRect(context, paintRect);
371
372         if (clip)
373             context->restore();
374     }
375 }
376
377 void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
378 {
379     RenderReplaced::paint(paintInfo, paintOffset);
380
381     if (paintInfo.phase == PaintPhaseOutline)
382         paintAreaElementFocusRing(paintInfo);
383 }
384
385 void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo)
386 {
387     Document& document = this->document();
388
389     if (document.printing() || !document.frame()->selection().isFocusedAndActive())
390         return;
391
392     if (paintInfo.context->paintingDisabled() && !paintInfo.context->updatingControlTints())
393         return;
394
395     Element* focusedElement = document.focusedElement();
396     if (!isHTMLAreaElement(focusedElement))
397         return;
398
399     HTMLAreaElement& areaElement = toHTMLAreaElement(*focusedElement);
400     if (areaElement.imageElement() != node())
401         return;
402
403     // Even if the theme handles focus ring drawing for entire elements, it won't do it for
404     // an area within an image, so we don't call RenderTheme::supportsFocusRing here.
405
406     Path path = areaElement.computePath(this);
407     if (path.isEmpty())
408         return;
409
410     RenderStyle* areaElementStyle = areaElement.computedStyle();
411     unsigned short outlineWidth = areaElementStyle->outlineWidth();
412     if (!outlineWidth)
413         return;
414
415     // FIXME: Clip path instead of context when Skia pathops is ready.
416     // https://crbug.com/251206
417     GraphicsContextStateSaver savedContext(*paintInfo.context);
418     paintInfo.context->clip(absoluteContentBox());
419     paintInfo.context->drawFocusRing(path, outlineWidth,
420         areaElementStyle->outlineOffset(),
421         resolveColor(areaElementStyle, CSSPropertyOutlineColor));
422 }
423
424 void RenderImage::areaElementFocusChanged(HTMLAreaElement* areaElement)
425 {
426     ASSERT(areaElement->imageElement() == node());
427
428     Path path = areaElement->computePath(this);
429     if (path.isEmpty())
430         return;
431
432     RenderStyle* areaElementStyle = areaElement->computedStyle();
433     unsigned short outlineWidth = areaElementStyle->outlineWidth();
434
435     IntRect repaintRect = enclosingIntRect(path.boundingRect());
436     repaintRect.moveBy(-absoluteContentBox().location());
437     repaintRect.inflate(outlineWidth);
438
439     repaintRectangle(repaintRect);
440 }
441
442 void RenderImage::paintIntoRect(GraphicsContext* context, const LayoutRect& rect)
443 {
444     IntRect alignedRect = pixelSnappedIntRect(rect);
445     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || alignedRect.width() <= 0 || alignedRect.height() <= 0)
446         return;
447
448     RefPtr<Image> img = m_imageResource->image(alignedRect.width(), alignedRect.height());
449     if (!img || img->isNull())
450         return;
451
452     HTMLImageElement* imageElt = isHTMLImageElement(node()) ? toHTMLImageElement(node()) : 0;
453     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
454     Image* image = m_imageResource->image().get();
455     InterpolationQuality interpolationQuality = chooseInterpolationQuality(context, image, image, alignedRect.size());
456
457     InspectorInstrumentation::willPaintImage(this);
458     InterpolationQuality previousInterpolationQuality = context->imageInterpolationQuality();
459     context->setImageInterpolationQuality(interpolationQuality);
460     context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), alignedRect, compositeOperator, shouldRespectImageOrientation());
461     context->setImageInterpolationQuality(previousInterpolationQuality);
462     InspectorInstrumentation::didPaintImage(this);
463 }
464
465 bool RenderImage::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox*) const
466 {
467     if (!RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(bleedAvoidance))
468         return false;
469
470     return !const_cast<RenderImage*>(this)->backgroundIsKnownToBeObscured();
471 }
472
473 bool RenderImage::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned) const
474 {
475     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
476         return false;
477     if (m_imageResource->cachedImage() && !m_imageResource->cachedImage()->isLoaded())
478         return false;
479     if (!contentBoxRect().contains(localRect))
480         return false;
481     EFillBox backgroundClip = style()->backgroundClip();
482     // Background paints under borders.
483     if (backgroundClip == BorderFillBox && style()->hasBorder() && !borderObscuresBackground())
484         return false;
485     // Background shows in padding area.
486     if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style()->hasPadding())
487         return false;
488     // Object-position may leave parts of the content box empty, regardless of the value of object-fit.
489     if (style()->objectPosition() != RenderStyle::initialObjectPosition())
490         return false;
491     // Object-fit may leave parts of the content box empty.
492     ObjectFit objectFit = style()->objectFit();
493     if (objectFit != ObjectFitFill && objectFit != ObjectFitCover)
494         return false;
495     // Check for image with alpha.
496     return m_imageResource->cachedImage() && m_imageResource->cachedImage()->currentFrameKnownToBeOpaque(this);
497 }
498
499 bool RenderImage::computeBackgroundIsKnownToBeObscured()
500 {
501     if (!hasBackground())
502         return false;
503
504     LayoutRect paintedExtent;
505     if (!getBackgroundPaintedExtent(paintedExtent))
506         return false;
507     return foregroundIsKnownToBeOpaqueInRect(paintedExtent, 0);
508 }
509
510 LayoutUnit RenderImage::minimumReplacedHeight() const
511 {
512     return m_imageResource->errorOccurred() ? intrinsicSize().height() : LayoutUnit();
513 }
514
515 HTMLMapElement* RenderImage::imageMap() const
516 {
517     HTMLImageElement* i = isHTMLImageElement(node()) ? toHTMLImageElement(node()) : 0;
518     return i ? i->treeScope().getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
519 }
520
521 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
522 {
523     HitTestResult tempResult(result.hitTestLocation());
524     bool inside = RenderReplaced::nodeAtPoint(request, tempResult, locationInContainer, accumulatedOffset, hitTestAction);
525
526     if (tempResult.innerNode() && node()) {
527         if (HTMLMapElement* map = imageMap()) {
528             LayoutRect contentBox = contentBoxRect();
529             float scaleFactor = 1 / style()->effectiveZoom();
530             LayoutPoint mapLocation = locationInContainer.point() - toLayoutSize(accumulatedOffset) - locationOffset() - toLayoutSize(contentBox.location());
531             mapLocation.scale(scaleFactor, scaleFactor);
532
533             if (map->mapMouseEvent(mapLocation, contentBox.size(), tempResult))
534                 tempResult.setInnerNonSharedNode(node());
535         }
536     }
537
538     if (!inside && result.isRectBasedTest())
539         result.append(tempResult);
540     if (inside)
541         result = tempResult;
542     return inside;
543 }
544
545 void RenderImage::updateAltText()
546 {
547     if (!node())
548         return;
549
550     if (isHTMLInputElement(*node()))
551         m_altText = toHTMLInputElement(node())->altText();
552     else if (isHTMLImageElement(*node()))
553         m_altText = toHTMLImageElement(node())->altText();
554 }
555
556 void RenderImage::layout()
557 {
558     RenderReplaced::layout();
559     updateInnerContentRect();
560 }
561
562 bool RenderImage::updateImageLoadingPriorities()
563 {
564     if (!m_imageResource || !m_imageResource->cachedImage() || m_imageResource->cachedImage()->isLoaded())
565         return false;
566
567     LayoutRect viewBounds = viewRect();
568     LayoutRect objectBounds = absoluteContentBox();
569
570     // The object bounds might be empty right now, so intersects will fail since it doesn't deal
571     // with empty rects. Use LayoutRect::contains in that case.
572     bool isVisible;
573     if (!objectBounds.isEmpty())
574         isVisible =  viewBounds.intersects(objectBounds);
575     else
576         isVisible = viewBounds.contains(objectBounds);
577
578     ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
579         ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
580
581     LayoutRect screenArea;
582     if (!objectBounds.isEmpty()) {
583         screenArea = viewBounds;
584         screenArea.intersect(objectBounds);
585     }
586
587     ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(m_imageResource->cachedImage(), status, screenArea);
588
589     return true;
590 }
591
592 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
593 {
594     RenderReplaced::computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
595
596     // Our intrinsicSize is empty if we're rendering generated images with relative width/height. Figure out the right intrinsic size to use.
597     if (intrinsicSize.isEmpty() && (m_imageResource->imageHasRelativeWidth() || m_imageResource->imageHasRelativeHeight())) {
598         RenderObject* containingBlock = isOutOfFlowPositioned() ? container() : this->containingBlock();
599         if (containingBlock->isBox()) {
600             RenderBox* box = toRenderBox(containingBlock);
601             intrinsicSize.setWidth(box->availableLogicalWidth().toFloat());
602             intrinsicSize.setHeight(box->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
603         }
604     }
605     // Don't compute an intrinsic ratio to preserve historical WebKit behavior if we're painting alt text and/or a broken image.
606     // Video is excluded from this behavior because video elements have a default aspect ratio that a failed poster image load should not override.
607     if (m_imageResource && m_imageResource->errorOccurred() && !isVideo()) {
608         intrinsicRatio = 1;
609         return;
610     }
611 }
612
613 bool RenderImage::needsPreferredWidthsRecalculation() const
614 {
615     if (RenderReplaced::needsPreferredWidthsRecalculation())
616         return true;
617     return embeddedContentBox();
618 }
619
620 RenderBox* RenderImage::embeddedContentBox() const
621 {
622     if (!m_imageResource)
623         return 0;
624
625     ImageResource* cachedImage = m_imageResource->cachedImage();
626     if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
627         return toSVGImage(cachedImage->image())->embeddedContentBox();
628
629     return 0;
630 }
631
632 } // namespace WebCore