441722e91de91f6a53717d5af486c783d2d38534
[WebKit-https.git] / Source / WebCore / 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  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  *
25  */
26
27 #include "config.h"
28 #include "RenderImage.h"
29
30 #include "BitmapImage.h"
31 #include "FontCache.h"
32 #include "Frame.h"
33 #include "FrameSelection.h"
34 #include "GraphicsContext.h"
35 #include "HTMLAreaElement.h"
36 #include "HTMLImageElement.h"
37 #include "HTMLInputElement.h"
38 #include "HTMLMapElement.h"
39 #include "HTMLNames.h"
40 #include "HitTestResult.h"
41 #include "Page.h"
42 #include "RenderLayer.h"
43 #include "RenderView.h"
44 #include "SVGImage.h"
45 #include <wtf/UnusedParam.h>
46
47 using namespace std;
48
49 namespace WebCore {
50
51 using namespace HTMLNames;
52
53 RenderImage::RenderImage(Node* node)
54     : RenderReplaced(node, IntSize())
55     , m_needsToSetSizeForAltText(false)
56     , m_didIncrementVisuallyNonEmptyPixelCount(false)
57     , m_isGeneratedContent(false)
58 {
59     updateAltText();
60 }
61
62 RenderImage::~RenderImage()
63 {
64     ASSERT(m_imageResource);
65     m_imageResource->shutdown();
66 }
67
68 void RenderImage::setImageResource(PassOwnPtr<RenderImageResource> imageResource)
69 {
70     ASSERT(!m_imageResource);
71     m_imageResource = imageResource;
72     m_imageResource->initialize(this);
73 }
74
75 // If we'll be displaying either alt text or an image, add some padding.
76 static const unsigned short paddingWidth = 4;
77 static const unsigned short paddingHeight = 4;
78
79 // Alt text is restricted to this maximum size, in pixels.  These are
80 // signed integers because they are compared with other signed values.
81 static const float maxAltTextWidth = 1024;
82 static const int maxAltTextHeight = 256;
83
84 IntSize RenderImage::imageSizeForError(CachedImage* newImage) const
85 {
86     ASSERT_ARG(newImage, newImage);
87     ASSERT_ARG(newImage, newImage->imageForRenderer(this));
88
89     IntSize imageSize;
90     if (newImage->willPaintBrokenImage()) {
91         float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
92         pair<Image*, float> brokenImageAndImageScaleFactor = newImage->brokenImage(deviceScaleFactor);
93         imageSize = brokenImageAndImageScaleFactor.first->size();
94         imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
95     } else
96         imageSize = newImage->imageForRenderer(this)->size();
97
98     // imageSize() returns 0 for the error image. We need the true size of the
99     // error image, so we have to get it by grabbing image() directly.
100     return IntSize(paddingWidth + imageSize.width() * style()->effectiveZoom(), paddingHeight + imageSize.height() * style()->effectiveZoom());
101 }
102
103 // Sets the image height and width to fit the alt text.  Returns true if the
104 // image size changed.
105 bool RenderImage::setImageSizeForAltText(CachedImage* newImage /* = 0 */)
106 {
107     IntSize imageSize;
108     if (newImage && newImage->imageForRenderer(this))
109         imageSize = imageSizeForError(newImage);
110     else if (!m_altText.isEmpty() || newImage) {
111         // If we'll be displaying either text or an image, add a little padding.
112         imageSize = IntSize(paddingWidth, paddingHeight);
113     }
114
115     // we have an alt and the user meant it (its not a text we invented)
116     if (!m_altText.isEmpty()) {
117         FontCachePurgePreventer fontCachePurgePreventer;
118
119         const Font& font = style()->font();
120         IntSize textSize(min(font.width(RenderBlock::constructTextRun(this, font, m_altText, style())), maxAltTextWidth), min(font.fontMetrics().height(), maxAltTextHeight));
121         imageSize = imageSize.expandedTo(textSize);
122     }
123
124     if (imageSize == intrinsicSize())
125         return false;
126
127     setIntrinsicSize(imageSize);
128     return true;
129 }
130
131 void RenderImage::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
132 {
133     RenderReplaced::styleDidChange(diff, oldStyle);
134     if (m_needsToSetSizeForAltText) {
135         if (!m_altText.isEmpty() && setImageSizeForAltText(m_imageResource->cachedImage()))
136             imageDimensionsChanged(true /* imageSizeChanged */);
137         m_needsToSetSizeForAltText = false;
138     }
139 }
140
141 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
142 {
143     if (documentBeingDestroyed())
144         return;
145
146     if (hasBoxDecorations() || hasMask())
147         RenderReplaced::imageChanged(newImage, rect);
148     
149     if (!m_imageResource)
150         return;
151
152     if (newImage != m_imageResource->imagePtr() || !newImage)
153         return;
154     
155     if (!m_didIncrementVisuallyNonEmptyPixelCount) {
156         view()->frameView()->incrementVisuallyNonEmptyPixelCount(m_imageResource->imageSize(1.0f));
157         m_didIncrementVisuallyNonEmptyPixelCount = true;
158     }
159
160     bool imageSizeChanged = false;
161
162     // Set image dimensions, taking into account the size of the alt text.
163     if (m_imageResource->errorOccurred()) {
164         if (!m_altText.isEmpty() && document()->isPendingStyleRecalc()) {
165             ASSERT(node());
166             if (node()) {
167                 m_needsToSetSizeForAltText = true;
168                 node()->setNeedsStyleRecalc(SyntheticStyleChange);
169             }
170             return;
171         }
172         imageSizeChanged = setImageSizeForAltText(m_imageResource->cachedImage());
173     }
174
175     imageDimensionsChanged(imageSizeChanged, rect);
176 }
177
178 bool RenderImage::updateIntrinsicSizeIfNeeded(const LayoutSize& newSize, bool imageSizeChanged)
179 {
180     if (newSize == intrinsicSize() && !imageSizeChanged)
181         return false;
182     if (m_imageResource->errorOccurred())
183         return imageSizeChanged;
184     setIntrinsicSize(newSize);
185     return true;
186 }
187
188 void RenderImage::imageDimensionsChanged(bool imageSizeChanged, const IntRect* rect)
189 {
190     bool shouldRepaint = true;
191     if (updateIntrinsicSizeIfNeeded(m_imageResource->imageSize(style()->effectiveZoom()), imageSizeChanged)) {
192         // In the case of generated image content using :before/:after, we might not be in the
193         // render tree yet.  In that case, we don't need to worry about check for layout, since we'll get a
194         // layout when we get added in to the render tree hierarchy later.
195         if (containingBlock()) {
196             // lets see if we need to relayout at all..
197             int oldwidth = width();
198             int oldheight = height();
199             if (!preferredLogicalWidthsDirty())
200                 setPreferredLogicalWidthsDirty(true);
201             computeLogicalWidth();
202             computeLogicalHeight();
203
204             if (imageSizeChanged || width() != oldwidth || height() != oldheight) {
205                 shouldRepaint = false;
206                 if (!selfNeedsLayout())
207                     setNeedsLayout(true);
208             }
209
210             setWidth(oldwidth);
211             setHeight(oldheight);
212         }
213     }
214
215     if (shouldRepaint) {
216         LayoutRect repaintRect;
217         if (rect) {
218             // The image changed rect is in source image coordinates (pre-zooming),
219             // so map from the bounds of the image to the contentsBox.
220             repaintRect = enclosingIntRect(mapRect(*rect, FloatRect(FloatPoint(), m_imageResource->imageSize(1.0f)), contentBoxRect()));
221             // Guard against too-large changed rects.
222             repaintRect.intersect(contentBoxRect());
223         } else
224             repaintRect = contentBoxRect();
225         
226         repaintRectangle(repaintRect);
227
228 #if USE(ACCELERATED_COMPOSITING)
229         if (hasLayer()) {
230             // Tell any potential compositing layers that the image needs updating.
231             layer()->contentChanged(RenderLayer::ImageChanged);
232         }
233 #endif
234     }
235 }
236
237 void RenderImage::notifyFinished(CachedResource* newImage)
238 {
239     if (!m_imageResource)
240         return;
241     
242     if (documentBeingDestroyed())
243         return;
244
245 #if USE(ACCELERATED_COMPOSITING)
246     if (newImage == m_imageResource->cachedImage() && hasLayer()) {
247         // tell any potential compositing layers
248         // that the image is done and they can reference it directly.
249         layer()->contentChanged(RenderLayer::ImageChanged);
250     }
251 #else
252     UNUSED_PARAM(newImage);
253 #endif
254 }
255
256 void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
257 {
258     LayoutUnit cWidth = contentWidth();
259     LayoutUnit cHeight = contentHeight();
260     LayoutUnit leftBorder = borderLeft();
261     LayoutUnit topBorder = borderTop();
262     LayoutUnit leftPad = paddingLeft();
263     LayoutUnit topPad = paddingTop();
264
265     GraphicsContext* context = paintInfo.context;
266
267     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
268         if (paintInfo.phase == PaintPhaseSelection)
269             return;
270
271         if (cWidth > 2 && cHeight > 2) {
272             // Draw an outline rect where the image should be.
273             context->setStrokeStyle(SolidStroke);
274             context->setStrokeColor(Color::lightGray, style()->colorSpace());
275             context->setFillColor(Color::transparent, style()->colorSpace());
276             context->drawRect(LayoutRect(paintOffset.x() + leftBorder + leftPad, paintOffset.y() + topBorder + topPad, cWidth, cHeight));
277
278             bool errorPictureDrawn = false;
279             LayoutSize imageOffset;
280             // When calculating the usable dimensions, exclude the pixels of
281             // the ouline rect so the error image/alt text doesn't draw on it.
282             LayoutUnit usableWidth = cWidth - 2;
283             LayoutUnit usableHeight = cHeight - 2;
284
285             RefPtr<Image> image = m_imageResource->image();
286
287             if (m_imageResource->errorOccurred() && !image->isNull() && usableWidth >= image->width() && usableHeight >= image->height()) {
288                 float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
289                 // Call brokenImage() explicitly to ensure we get the broken image icon at the appropriate resolution.
290                 pair<Image*, float> brokenImageAndImageScaleFactor = m_imageResource->cachedImage()->brokenImage(deviceScaleFactor);
291                 image = brokenImageAndImageScaleFactor.first;
292                 IntSize imageSize = image->size();
293                 imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
294                 // Center the error image, accounting for border and padding.
295                 LayoutUnit centerX = (usableWidth - imageSize.width()) / 2;
296                 if (centerX < 0)
297                     centerX = 0;
298                 LayoutUnit centerY = (usableHeight - imageSize.height()) / 2;
299                 if (centerY < 0)
300                     centerY = 0;
301                 imageOffset = LayoutSize(leftBorder + leftPad + centerX + 1, topBorder + topPad + centerY + 1);
302                 context->drawImage(image.get(), style()->colorSpace(), IntRect(paintOffset + imageOffset, imageSize));
303                 errorPictureDrawn = true;
304             }
305
306             if (!m_altText.isEmpty()) {
307                 String text = document()->displayStringModifiedByEncoding(m_altText);
308                 context->setFillColor(style()->visitedDependentColor(CSSPropertyColor), style()->colorSpace());
309                 const Font& font = style()->font();
310                 const FontMetrics& fontMetrics = font.fontMetrics();
311                 LayoutUnit ascent = fontMetrics.ascent();
312                 LayoutPoint altTextOffset = paintOffset;
313                 altTextOffset.move(leftBorder + leftPad, topBorder + topPad + ascent);
314
315                 // Only draw the alt text if it'll fit within the content box,
316                 // and only if it fits above the error image.
317                 TextRun textRun = RenderBlock::constructTextRun(this, font, text, style());
318                 LayoutUnit textWidth = font.width(textRun);
319                 if (errorPictureDrawn) {
320                     if (usableWidth >= textWidth && fontMetrics.height() <= imageOffset.height())
321                         context->drawText(font, textRun, altTextOffset);
322                 } else if (usableWidth >= textWidth && cHeight >= fontMetrics.height())
323                     context->drawText(font, textRun, altTextOffset);
324             }
325         }
326     } else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
327         RefPtr<Image> img = m_imageResource->image(cWidth, cHeight);
328         if (!img || img->isNull())
329             return;
330
331 #if PLATFORM(MAC)
332         if (style()->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
333             paintCustomHighlight(toPoint(paintOffset - location()), style()->highlight(), true);
334 #endif
335
336         LayoutSize contentSize(cWidth, cHeight);
337         LayoutPoint contentLocation = paintOffset;
338         contentLocation.move(leftBorder + leftPad, topBorder + topPad);
339         paintIntoRect(context, LayoutRect(contentLocation, contentSize));
340     }
341 }
342
343 void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
344 {
345     RenderReplaced::paint(paintInfo, paintOffset);
346     
347     if (paintInfo.phase == PaintPhaseOutline)
348         paintAreaElementFocusRing(paintInfo);
349 }
350     
351 void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo)
352 {
353     Document* document = this->document();
354     
355     if (document->printing() || !document->frame()->selection()->isFocusedAndActive())
356         return;
357     
358     if (paintInfo.context->paintingDisabled() && !paintInfo.context->updatingControlTints())
359         return;
360
361     Node* focusedNode = document->focusedNode();
362     if (!focusedNode || !focusedNode->hasTagName(areaTag))
363         return;
364
365     HTMLAreaElement* areaElement = static_cast<HTMLAreaElement*>(focusedNode);
366     if (areaElement->imageElement() != node())
367         return;
368
369     // Even if the theme handles focus ring drawing for entire elements, it won't do it for
370     // an area within an image, so we don't call RenderTheme::supportsFocusRing here.
371
372     Path path = areaElement->computePath(this);
373     if (path.isEmpty())
374         return;
375
376     // FIXME: Do we need additional code to clip the path to the image's bounding box?
377
378     RenderStyle* areaElementStyle = areaElement->computedStyle();
379     unsigned short outlineWidth = areaElementStyle->outlineWidth();
380     if (!outlineWidth)
381         return;
382
383     paintInfo.context->drawFocusRing(path, outlineWidth,
384         areaElementStyle->outlineOffset(),
385         areaElementStyle->visitedDependentColor(CSSPropertyOutlineColor));
386 }
387
388 void RenderImage::areaElementFocusChanged(HTMLAreaElement* element)
389 {
390     ASSERT_UNUSED(element, element->imageElement() == node());
391
392     // It would be more efficient to only repaint the focus ring rectangle
393     // for the passed-in area element. That would require adding functions
394     // to the area element class.
395     repaint();
396 }
397
398 void RenderImage::paintIntoRect(GraphicsContext* context, const LayoutRect& rect)
399 {
400     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || rect.width() <= 0 || rect.height() <= 0)
401         return;
402
403     RefPtr<Image> img = m_imageResource->image(rect.width(), rect.height());
404     if (!img || img->isNull())
405         return;
406
407     HTMLImageElement* imageElt = (node() && node()->hasTagName(imgTag)) ? static_cast<HTMLImageElement*>(node()) : 0;
408     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
409     Image* image = m_imageResource->image().get();
410     bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, rect.size());
411     context->drawImage(m_imageResource->image(rect.width(), rect.height()).get(), style()->colorSpace(), rect, compositeOperator, useLowQualityScaling);
412 }
413
414 bool RenderImage::backgroundIsObscured() const
415 {
416     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
417         return false;
418
419     if (m_imageResource->cachedImage() && !m_imageResource->cachedImage()->isLoaded())
420         return false;
421
422     EFillBox backgroundClip = style()->backgroundClip();
423
424     // Background paints under borders.
425     if (backgroundClip == BorderFillBox && style()->hasBorder() && !borderObscuresBackground())
426         return false;
427
428     // Background shows in padding area.
429     if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style()->hasPadding())
430         return false;
431
432     // Check for bitmap image with alpha.
433     Image* image = m_imageResource->image().get();
434     if (!image || !image->isBitmapImage() || image->currentFrameHasAlpha())
435         return false;
436         
437     return true;
438 }
439
440 int RenderImage::minimumReplacedHeight() const
441 {
442     return m_imageResource->errorOccurred() ? intrinsicSize().height() : 0;
443 }
444
445 HTMLMapElement* RenderImage::imageMap() const
446 {
447     HTMLImageElement* i = node() && node()->hasTagName(imgTag) ? static_cast<HTMLImageElement*>(node()) : 0;
448     return i ? i->treeScope()->getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
449 }
450
451 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
452 {
453     HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
454     bool inside = RenderReplaced::nodeAtPoint(request, tempResult, pointInContainer, accumulatedOffset, hitTestAction);
455
456     if (tempResult.innerNode() && node()) {
457         if (HTMLMapElement* map = imageMap()) {
458             LayoutRect contentBox = contentBoxRect();
459             float scaleFactor = 1 / style()->effectiveZoom();
460             LayoutPoint mapLocation(pointInContainer.x() - accumulatedOffset.x() - this->x() - contentBox.x(), pointInContainer.y() - accumulatedOffset.y() - this->y() - contentBox.y());
461             mapLocation.scale(scaleFactor, scaleFactor);
462             
463             if (map->mapMouseEvent(mapLocation, contentBox.size(), tempResult))
464                 tempResult.setInnerNonSharedNode(node());
465         }
466     }
467
468     if (!inside && result.isRectBasedTest())
469         result.append(tempResult);
470     if (inside)
471         result = tempResult;
472     return inside;
473 }
474
475 void RenderImage::updateAltText()
476 {
477     if (!node())
478         return;
479
480     if (node()->hasTagName(inputTag))
481         m_altText = static_cast<HTMLInputElement*>(node())->altText();
482     else if (node()->hasTagName(imgTag))
483         m_altText = static_cast<HTMLImageElement*>(node())->altText();
484 }
485
486 LayoutUnit RenderImage::computeReplacedLogicalWidth(bool includeMaxWidth) const
487 {
488     // If we've got an explicit width/height assigned, propagate it to the image resource.    
489     if (style()->logicalWidth().isFixed() && style()->logicalHeight().isFixed()) {
490         LayoutUnit width = RenderReplaced::computeReplacedLogicalWidth(includeMaxWidth);
491         m_imageResource->setContainerSizeForRenderer(IntSize(width, computeReplacedLogicalHeight()));
492         return width;
493     }
494
495     RenderBox* contentRenderer = embeddedContentBox();
496     bool hasRelativeWidth = contentRenderer ? contentRenderer->style()->width().isPercent() : m_imageResource->imageHasRelativeWidth();
497     bool hasRelativeHeight = contentRenderer ? contentRenderer->style()->height().isPercent() : m_imageResource->imageHasRelativeHeight();
498
499     IntSize containerSize;
500     if (hasRelativeWidth || hasRelativeHeight) {
501         // Propagate the containing block size to the image resource, otherwhise we can't compute our own intrinsic size, if it's relative.
502         RenderObject* containingBlock = isPositioned() ? container() : this->containingBlock();
503         if (containingBlock->isBox()) {
504             RenderBox* box = toRenderBox(containingBlock);
505             containerSize = IntSize(box->availableWidth(), box->availableHeight()); // Already contains zooming information.
506         }
507     } else {
508         // Propagate the current zoomed image size to the image resource, otherwhise the image size will remain the same on-screen.
509         CachedImage* cachedImage = m_imageResource->cachedImage();
510         if (cachedImage && cachedImage->image()) {
511             containerSize = cachedImage->image()->size();
512             // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
513             containerSize.setWidth(static_cast<LayoutUnit>(containerSize.width() * style()->effectiveZoom()));
514             containerSize.setHeight(static_cast<LayoutUnit>(containerSize.height() * style()->effectiveZoom()));
515         }
516     }
517
518     if (!containerSize.isEmpty()) {
519         m_imageResource->setContainerSizeForRenderer(containerSize);
520         const_cast<RenderImage*>(this)->updateIntrinsicSizeIfNeeded(containerSize, false);
521     }
522
523     return RenderReplaced::computeReplacedLogicalWidth(includeMaxWidth);
524 }
525
526 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicRatio, bool& isPercentageIntrinsicSize) const
527 {
528     // Assure this method is never used for SVGImages.
529     ASSERT(!embeddedContentBox());
530     isPercentageIntrinsicSize = false;
531     CachedImage* cachedImage = m_imageResource ? m_imageResource->cachedImage() : 0;
532     if (cachedImage && cachedImage->image())
533         intrinsicRatio = cachedImage->image()->size();
534 }
535
536 bool RenderImage::needsPreferredWidthsRecalculation() const
537 {
538     if (RenderReplaced::needsPreferredWidthsRecalculation())
539         return true;
540     return embeddedContentBox();
541 }
542
543 RenderBox* RenderImage::embeddedContentBox() const
544 {
545     if (!m_imageResource)
546         return 0;
547
548 #if ENABLE(SVG)
549     CachedImage* cachedImage = m_imageResource->cachedImage();
550     if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
551         return static_cast<SVGImage*>(cachedImage->image())->embeddedContentBox();
552 #endif
553
554     return 0;
555 }
556
557 } // namespace WebCore