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