Upstream version 9.38.198.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 "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"
52
53 namespace blink {
54
55 float deviceScaleFactor(LocalFrame*);
56
57 using namespace HTMLNames;
58
59 RenderImage::RenderImage(Element* element)
60     : RenderReplaced(element, IntSize())
61     , m_didIncrementVisuallyNonEmptyPixelCount(false)
62     , m_isGeneratedContent(false)
63     , m_imageDevicePixelRatio(1.0f)
64 {
65     updateAltText();
66     ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
67 }
68
69 RenderImage* RenderImage::createAnonymous(Document* document)
70 {
71     RenderImage* image = new RenderImage(0);
72     image->setDocumentForAnonymous(document);
73     return image;
74 }
75
76 RenderImage::~RenderImage()
77 {
78 }
79
80 void RenderImage::destroy()
81 {
82     ASSERT(m_imageResource);
83     m_imageResource->shutdown();
84     RenderReplaced::destroy();
85 }
86
87 void RenderImage::setImageResource(PassOwnPtr<RenderImageResource> imageResource)
88 {
89     ASSERT(!m_imageResource);
90     m_imageResource = imageResource;
91     m_imageResource->initialize(this);
92 }
93
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;
97
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;
102
103 IntSize RenderImage::imageSizeForError(ImageResource* newImage) const
104 {
105     ASSERT_ARG(newImage, newImage);
106     ASSERT_ARG(newImage, newImage->imageForRenderer(this));
107
108     IntSize imageSize;
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);
114     } else
115         imageSize = newImage->imageForRenderer(this)->size();
116
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());
120 }
121
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 */)
125 {
126     IntSize imageSize;
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);
132     }
133
134     // we have an alt and the user meant it (its not a text we invented)
135     if (!m_altText.isEmpty()) {
136         FontCachePurgePreventer fontCachePurgePreventer;
137
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);
141     }
142
143     if (imageSize == intrinsicSize())
144         return false;
145
146     setIntrinsicSize(imageSize);
147     return true;
148 }
149
150 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
151 {
152     if (documentBeingDestroyed())
153         return;
154
155     if (hasBoxDecorationBackground() || hasMask() || hasShapeOutside())
156         RenderReplaced::imageChanged(newImage, rect);
157
158     if (!m_imageResource)
159         return;
160
161     if (newImage != m_imageResource->imagePtr())
162         return;
163
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();
168
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;
173     }
174
175     bool imageSizeChanged = false;
176
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());
180
181     repaintOrMarkForLayout(imageSizeChanged, rect);
182 }
183
184 void RenderImage::updateIntrinsicSizeIfNeeded(const LayoutSize& newSize)
185 {
186     if (m_imageResource->errorOccurred() || !m_imageResource->hasImage())
187         return;
188     setIntrinsicSize(newSize);
189 }
190
191 void RenderImage::updateInnerContentRect()
192 {
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);
198 }
199
200 void RenderImage::repaintOrMarkForLayout(bool imageSizeChangedToAccomodateAltText, const IntRect* rect)
201 {
202     LayoutSize oldIntrinsicSize = intrinsicSize();
203     LayoutSize newIntrinsicSize = m_imageResource->intrinsicSize(style()->effectiveZoom());
204     updateIntrinsicSizeIfNeeded(newIntrinsicSize);
205
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())
211         return;
212
213     bool imageSourceHasChangedSize = oldIntrinsicSize != newIntrinsicSize || imageSizeChangedToAccomodateAltText;
214     if (imageSourceHasChangedSize)
215         setPreferredLogicalWidthsDirty();
216
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();
219
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();
224
225     if (imageSourceHasChangedSize && (!imageSizeIsConstrained || containingBlockNeedsToRecomputePreferredSize)) {
226         setNeedsLayoutAndFullPaintInvalidation();
227         return;
228     }
229
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();
237     }
238
239     LayoutRect repaintRect;
240     if (rect) {
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());
247     } else {
248         repaintRect = contentBoxRect();
249     }
250
251     {
252         // FIXME: We should not be allowing repaint during layout. crbug.com/339584
253         AllowPaintInvalidationScope scoper(frameView());
254         invalidatePaintRectangle(repaintRect);
255     }
256
257     // Tell any potential compositing layers that the image needs updating.
258     contentChanged(ImageChanged);
259 }
260
261 void RenderImage::notifyFinished(Resource* newImage)
262 {
263     if (!m_imageResource)
264         return;
265
266     if (documentBeingDestroyed())
267         return;
268
269     invalidateBackgroundObscurationStatus();
270
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);
275     }
276 }
277
278 void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
279 {
280     LayoutUnit cWidth = contentWidth();
281     LayoutUnit cHeight = contentHeight();
282     LayoutUnit leftBorder = borderLeft();
283     LayoutUnit topBorder = borderTop();
284     LayoutUnit leftPad = paddingLeft();
285     LayoutUnit topPad = paddingTop();
286
287     GraphicsContext* context = paintInfo.context;
288
289     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
290         if (paintInfo.phase == PaintPhaseSelection)
291             return;
292
293         if (cWidth > 2 && cHeight > 2) {
294             const int borderWidth = 1;
295
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)));
301
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;
308
309             RefPtr<Image> image = m_imageResource->image();
310
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;
320                 if (centerX < 0)
321                     centerX = 0;
322                 LayoutUnit centerY = (usableHeight - imageSize.height()) / 2;
323                 if (centerY < 0)
324                     centerY = 0;
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;
328             }
329
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);
337
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);
348                 }
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);
354                 }
355             }
356         }
357     } else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
358         RefPtr<Image> img = m_imageResource->image(cWidth, cHeight);
359         if (!img || img->isNull())
360             return;
361
362         LayoutRect contentRect = contentBoxRect();
363         contentRect.moveBy(paintOffset);
364         LayoutRect paintRect = replacedContentRect();
365         paintRect.moveBy(paintOffset);
366         bool clip = !contentRect.contains(paintRect);
367         if (clip) {
368             context->save();
369             context->clip(contentRect);
370         }
371
372         paintIntoRect(context, paintRect);
373
374         if (clip)
375             context->restore();
376     }
377 }
378
379 void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
380 {
381     RenderReplaced::paint(paintInfo, paintOffset);
382
383     if (paintInfo.phase == PaintPhaseOutline)
384         paintAreaElementFocusRing(paintInfo);
385 }
386
387 void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo)
388 {
389     Document& document = this->document();
390
391     if (document.printing() || !document.frame()->selection().isFocusedAndActive())
392         return;
393
394     Element* focusedElement = document.focusedElement();
395     if (!isHTMLAreaElement(focusedElement))
396         return;
397
398     HTMLAreaElement& areaElement = toHTMLAreaElement(*focusedElement);
399     if (areaElement.imageElement() != node())
400         return;
401
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.
404
405     Path path = areaElement.computePath(this);
406     if (path.isEmpty())
407         return;
408
409     RenderStyle* areaElementStyle = areaElement.computedStyle();
410     unsigned short outlineWidth = areaElementStyle->outlineWidth();
411     if (!outlineWidth)
412         return;
413
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));
421 }
422
423 void RenderImage::areaElementFocusChanged(HTMLAreaElement* areaElement)
424 {
425     ASSERT(areaElement->imageElement() == node());
426
427     Path path = areaElement->computePath(this);
428     if (path.isEmpty())
429         return;
430
431     RenderStyle* areaElementStyle = areaElement->computedStyle();
432     unsigned short outlineWidth = areaElementStyle->outlineWidth();
433
434     IntRect repaintRect = enclosingIntRect(path.boundingRect());
435     repaintRect.moveBy(-absoluteContentBox().location());
436     repaintRect.inflate(outlineWidth);
437
438     invalidatePaintRectangle(repaintRect);
439 }
440
441 void RenderImage::paintIntoRect(GraphicsContext* context, const LayoutRect& rect)
442 {
443     IntRect alignedRect = pixelSnappedIntRect(rect);
444     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || alignedRect.width() <= 0 || alignedRect.height() <= 0)
445         return;
446
447     RefPtr<Image> img = m_imageResource->image(alignedRect.width(), alignedRect.height());
448     if (!img || img->isNull())
449         return;
450
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());
455
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);
464 }
465
466 bool RenderImage::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox*) const
467 {
468     if (!RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(bleedAvoidance))
469         return false;
470
471     return !const_cast<RenderImage*>(this)->boxDecorationBackgroundIsKnownToBeObscured();
472 }
473
474 bool RenderImage::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned) const
475 {
476     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
477         return false;
478     if (m_imageResource->cachedImage() && !m_imageResource->cachedImage()->isLoaded())
479         return false;
480     if (!contentBoxRect().contains(localRect))
481         return false;
482     EFillBox backgroundClip = style()->backgroundClip();
483     // Background paints under borders.
484     if (backgroundClip == BorderFillBox && style()->hasBorder() && !borderObscuresBackground())
485         return false;
486     // Background shows in padding area.
487     if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style()->hasPadding())
488         return false;
489     // Object-position may leave parts of the content box empty, regardless of the value of object-fit.
490     if (style()->objectPosition() != RenderStyle::initialObjectPosition())
491         return false;
492     // Object-fit may leave parts of the content box empty.
493     ObjectFit objectFit = style()->objectFit();
494     if (objectFit != ObjectFitFill && objectFit != ObjectFitCover)
495         return false;
496     // Check for image with alpha.
497     return m_imageResource->cachedImage() && m_imageResource->cachedImage()->currentFrameKnownToBeOpaque(this);
498 }
499
500 bool RenderImage::computeBackgroundIsKnownToBeObscured()
501 {
502     if (!hasBackground())
503         return false;
504
505     LayoutRect paintedExtent;
506     if (!getBackgroundPaintedExtent(paintedExtent))
507         return false;
508     return foregroundIsKnownToBeOpaqueInRect(paintedExtent, 0);
509 }
510
511 LayoutUnit RenderImage::minimumReplacedHeight() const
512 {
513     return m_imageResource->errorOccurred() ? intrinsicSize().height() : LayoutUnit();
514 }
515
516 HTMLMapElement* RenderImage::imageMap() const
517 {
518     HTMLImageElement* i = isHTMLImageElement(node()) ? toHTMLImageElement(node()) : 0;
519     return i ? i->treeScope().getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
520 }
521
522 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
523 {
524     HitTestResult tempResult(result.hitTestLocation());
525     bool inside = RenderReplaced::nodeAtPoint(request, tempResult, locationInContainer, accumulatedOffset, hitTestAction);
526
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);
533
534             if (map->mapMouseEvent(mapLocation, contentBox.size(), tempResult))
535                 tempResult.setInnerNonSharedNode(node());
536         }
537     }
538
539     if (!inside && result.isRectBasedTest())
540         result.append(tempResult);
541     if (inside)
542         result = tempResult;
543     return inside;
544 }
545
546 void RenderImage::updateAltText()
547 {
548     if (!node())
549         return;
550
551     if (isHTMLInputElement(*node()))
552         m_altText = toHTMLInputElement(node())->altText();
553     else if (isHTMLImageElement(*node()))
554         m_altText = toHTMLImageElement(node())->altText();
555 }
556
557 void RenderImage::layout()
558 {
559     LayoutRect oldContentRect = replacedContentRect();
560     RenderReplaced::layout();
561     if (replacedContentRect() != oldContentRect) {
562         setShouldDoFullPaintInvalidation(true);
563         updateInnerContentRect();
564     }
565 }
566
567 bool RenderImage::updateImageLoadingPriorities()
568 {
569     if (!m_imageResource || !m_imageResource->cachedImage() || m_imageResource->cachedImage()->isLoaded())
570         return false;
571
572     LayoutRect viewBounds = viewRect();
573     LayoutRect objectBounds = absoluteContentBox();
574
575     // The object bounds might be empty right now, so intersects will fail since it doesn't deal
576     // with empty rects. Use LayoutRect::contains in that case.
577     bool isVisible;
578     if (!objectBounds.isEmpty())
579         isVisible =  viewBounds.intersects(objectBounds);
580     else
581         isVisible = viewBounds.contains(objectBounds);
582
583     ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
584         ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
585
586     LayoutRect screenArea;
587     if (!objectBounds.isEmpty()) {
588         screenArea = viewBounds;
589         screenArea.intersect(objectBounds);
590     }
591
592     ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(m_imageResource->cachedImage(), status, screenArea);
593
594     return true;
595 }
596
597 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
598 {
599     RenderReplaced::computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
600
601     // Our intrinsicSize is empty if we're rendering generated images with relative width/height. Figure out the right intrinsic size to use.
602     if (intrinsicSize.isEmpty() && (m_imageResource->imageHasRelativeWidth() || m_imageResource->imageHasRelativeHeight())) {
603         RenderObject* containingBlock = isOutOfFlowPositioned() ? container() : this->containingBlock();
604         if (containingBlock->isBox()) {
605             RenderBox* box = toRenderBox(containingBlock);
606             intrinsicSize.setWidth(box->availableLogicalWidth().toFloat());
607             intrinsicSize.setHeight(box->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
608         }
609     }
610     // Don't compute an intrinsic ratio to preserve historical WebKit behavior if we're painting alt text and/or a broken image.
611     // Video is excluded from this behavior because video elements have a default aspect ratio that a failed poster image load should not override.
612     if (m_imageResource && m_imageResource->errorOccurred() && !isVideo()) {
613         intrinsicRatio = 1;
614         return;
615     }
616 }
617
618 bool RenderImage::needsPreferredWidthsRecalculation() const
619 {
620     if (RenderReplaced::needsPreferredWidthsRecalculation())
621         return true;
622     return embeddedContentBox();
623 }
624
625 RenderBox* RenderImage::embeddedContentBox() const
626 {
627     if (!m_imageResource)
628         return 0;
629
630     ImageResource* cachedImage = m_imageResource->cachedImage();
631     if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
632         return toSVGImage(cachedImage->image())->embeddedContentBox();
633
634     return 0;
635 }
636
637 } // namespace blink