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