376ffefcab37ef862452a8bafb42f9af2dd4caa4
[WebKit-https.git] / 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 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 "Frame.h"
31 #include "GraphicsContext.h"
32 #include "HTMLAreaElement.h"
33 #include "HTMLCollection.h"
34 #include "HTMLImageElement.h"
35 #include "HTMLInputElement.h"
36 #include "HTMLMapElement.h"
37 #include "HTMLNames.h"
38 #include "HitTestResult.h"
39 #include "Page.h"
40 #include "RenderLayer.h"
41 #include "RenderTheme.h"
42 #include "RenderView.h"
43 #include "SelectionController.h"
44 #include <wtf/CurrentTime.h>
45 #include <wtf/UnusedParam.h>
46
47 #if ENABLE(WML)
48 #include "WMLImageElement.h"
49 #include "WMLNames.h"
50 #endif
51
52 using namespace std;
53
54 namespace WebCore {
55
56 using namespace HTMLNames;
57
58 RenderImage::RenderImage(Node* node)
59     : RenderReplaced(node, IntSize(0, 0))
60     , m_needsToSetSizeForAltText(false)
61 {
62     updateAltText();
63
64     view()->frameView()->setIsVisuallyNonEmpty();
65 }
66
67 RenderImage::~RenderImage()
68 {
69     ASSERT(m_imageResource);
70     m_imageResource->shutdown();
71 }
72
73 void RenderImage::setImageResource(PassOwnPtr<RenderImageResource> imageResource)
74 {
75     ASSERT(!m_imageResource);
76     m_imageResource = imageResource;
77     m_imageResource->initialize(this);
78 }
79
80 // If we'll be displaying either alt text or an image, add some padding.
81 static const unsigned short paddingWidth = 4;
82 static const unsigned short paddingHeight = 4;
83
84 // Alt text is restricted to this maximum size, in pixels.  These are
85 // signed integers because they are compared with other signed values.
86 static const int maxAltTextWidth = 1024;
87 static const int maxAltTextHeight = 256;
88
89 IntSize RenderImage::imageSizeForError(CachedImage* newImage) const
90 {
91     ASSERT_ARG(newImage, newImage);
92     ASSERT_ARG(newImage, newImage->image());
93
94     // imageSize() returns 0 for the error image. We need the true size of the
95     // error image, so we have to get it by grabbing image() directly.
96     return IntSize(paddingWidth + newImage->image()->width() * style()->effectiveZoom(), paddingHeight + newImage->image()->height() * style()->effectiveZoom());
97 }
98
99 // Sets the image height and width to fit the alt text.  Returns true if the
100 // image size changed.
101 bool RenderImage::setImageSizeForAltText(CachedImage* newImage /* = 0 */)
102 {
103     IntSize imageSize;
104     if (newImage && newImage->image())
105         imageSize = imageSizeForError(newImage);
106     else if (!m_altText.isEmpty() || newImage) {
107         // If we'll be displaying either text or an image, add a little padding.
108         imageSize = IntSize(paddingWidth, paddingHeight);
109     }
110
111     // we have an alt and the user meant it (its not a text we invented)
112     if (!m_altText.isEmpty()) {
113         const Font& font = style()->font();
114         IntSize textSize(min(font.width(TextRun(m_altText.characters(), m_altText.length())), maxAltTextWidth), min(font.height(), maxAltTextHeight));
115         imageSize = imageSize.expandedTo(textSize);
116     }
117
118     if (imageSize == intrinsicSize())
119         return false;
120
121     setIntrinsicSize(imageSize);
122     return true;
123 }
124
125 void RenderImage::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
126 {
127     RenderReplaced::styleDidChange(diff, oldStyle);
128     if (m_needsToSetSizeForAltText) {
129         if (!m_altText.isEmpty() && setImageSizeForAltText(m_imageResource->cachedImage()))
130             imageDimensionsChanged(true /* imageSizeChanged */);
131         m_needsToSetSizeForAltText = false;
132     }
133 }
134
135 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
136 {
137     if (documentBeingDestroyed())
138         return;
139
140     if (hasBoxDecorations() || hasMask())
141         RenderReplaced::imageChanged(newImage, rect);
142     
143     if (!m_imageResource)
144         return;
145
146     if (newImage != m_imageResource->imagePtr() || !newImage)
147         return;
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()->rendererContentChanged();
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()->rendererContentChanged();
233     }
234 #else
235     UNUSED_PARAM(newImage);
236 #endif
237 }
238
239 void RenderImage::paintReplaced(PaintInfo& paintInfo, int tx, int ty)
240 {
241     int cWidth = contentWidth();
242     int cHeight = contentHeight();
243     int leftBorder = borderLeft();
244     int topBorder = borderTop();
245     int leftPad = paddingLeft();
246     int 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(IntRect(tx + leftBorder + leftPad, ty + topBorder + topPad, cWidth, cHeight));
260
261             bool errorPictureDrawn = false;
262             int imageX = 0;
263             int imageY = 0;
264             // When calculating the usable dimensions, exclude the pixels of
265             // the ouline rect so the error image/alt text doesn't draw on it.
266             int usableWidth = cWidth - 2;
267             int usableHeight = cHeight - 2;
268
269             Image* image = m_imageResource->image();
270
271             if (m_imageResource->errorOccurred() && !image->isNull() && usableWidth >= image->width() && usableHeight >= image->height()) {
272                 // Center the error image, accounting for border and padding.
273                 int centerX = (usableWidth - image->width()) / 2;
274                 if (centerX < 0)
275                     centerX = 0;
276                 int centerY = (usableHeight - image->height()) / 2;
277                 if (centerY < 0)
278                     centerY = 0;
279                 imageX = leftBorder + leftPad + centerX + 1;
280                 imageY = topBorder + topPad + centerY + 1;
281                 context->drawImage(image, style()->colorSpace(), IntPoint(tx + imageX, ty + imageY));
282                 errorPictureDrawn = true;
283             }
284
285             if (!m_altText.isEmpty()) {
286                 String text = document()->displayStringModifiedByEncoding(m_altText);
287                 context->setFillColor(style()->visitedDependentColor(CSSPropertyColor), style()->colorSpace());
288                 int ax = tx + leftBorder + leftPad;
289                 int ay = ty + topBorder + topPad;
290                 const Font& font = style()->font();
291                 int ascent = font.ascent();
292
293                 // Only draw the alt text if it'll fit within the content box,
294                 // and only if it fits above the error image.
295                 TextRun textRun(text.characters(), text.length());
296                 int textWidth = font.width(textRun);
297                 if (errorPictureDrawn) {
298                     if (usableWidth >= textWidth && font.height() <= imageY)
299                         context->drawText(style()->font(), textRun, IntPoint(ax, ay + ascent));
300                 } else if (usableWidth >= textWidth && cHeight >= font.height())
301                     context->drawText(style()->font(), textRun, IntPoint(ax, ay + ascent));
302             }
303         }
304     } else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
305         Image* img = m_imageResource->image(cWidth, cHeight);
306         if (!img || img->isNull())
307             return;
308
309 #if PLATFORM(MAC)
310         if (style()->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
311             paintCustomHighlight(tx - x(), ty - y(), style()->highlight(), true);
312 #endif
313
314         IntSize contentSize(cWidth, cHeight);
315         IntRect rect(IntPoint(tx + leftBorder + leftPad, ty + topBorder + topPad), contentSize);
316         paintIntoRect(context, rect);
317     }
318 }
319
320 void RenderImage::paint(PaintInfo& paintInfo, int tx, int ty)
321 {
322     RenderReplaced::paint(paintInfo, tx, ty);
323     
324     if (paintInfo.phase == PaintPhaseOutline)
325         paintFocusRing(paintInfo, style());
326 }
327     
328 void RenderImage::paintFocusRing(PaintInfo& paintInfo, const RenderStyle* style)
329 {
330     // Don't draw focus rings if printing.
331     if (document()->printing() || !frame()->selection()->isFocusedAndActive())
332         return;
333     
334     if (paintInfo.context->paintingDisabled() && !paintInfo.context->updatingControlTints())
335         return;
336
337     HTMLMapElement* mapElement = imageMap();
338     if (!mapElement)
339         return;
340     
341     Document* document = mapElement->document();
342     if (!document)
343         return;
344     
345     Node* focusedNode = document->focusedNode();
346     if (!focusedNode)
347         return;
348     
349     RefPtr<HTMLCollection> areas = mapElement->areas();
350     unsigned numAreas = areas->length();
351
352     if (theme()->supportsFocusRing(style))
353         return; // The theme draws the focus ring.
354     
355     // FIXME: Clip the paths to the image bounding box.
356     for (unsigned k = 0; k < numAreas; ++k) {
357         HTMLAreaElement* areaElement = static_cast<HTMLAreaElement*>(areas->item(k));
358         if (focusedNode != areaElement)
359             continue;
360         
361         paintInfo.context->drawFocusRing(areaElement->getPath(this), style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
362         break;
363     }
364 }
365     
366 void RenderImage::paintIntoRect(GraphicsContext* context, const IntRect& rect)
367 {
368     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || rect.width() <= 0 || rect.height() <= 0)
369         return;
370
371     Image* img = m_imageResource->image(rect.width(), rect.height());
372     if (!img || img->isNull())
373         return;
374
375     HTMLImageElement* imageElt = (node() && node()->hasTagName(imgTag)) ? static_cast<HTMLImageElement*>(node()) : 0;
376     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
377     bool useLowQualityScaling = shouldPaintAtLowQuality(context, m_imageResource->image(), 0, rect.size());
378     context->drawImage(m_imageResource->image(rect.width(), rect.height()), style()->colorSpace(), rect, compositeOperator, useLowQualityScaling);
379 }
380
381 int RenderImage::minimumReplacedHeight() const
382 {
383     return m_imageResource->errorOccurred() ? intrinsicSize().height() : 0;
384 }
385
386 HTMLMapElement* RenderImage::imageMap() const
387 {
388     HTMLImageElement* i = node() && node()->hasTagName(imgTag) ? static_cast<HTMLImageElement*>(node()) : 0;
389     return i ? i->document()->getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
390 }
391
392 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty, HitTestAction hitTestAction)
393 {
394     HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
395     bool inside = RenderReplaced::nodeAtPoint(request, tempResult, x, y, tx, ty, hitTestAction);
396
397     if (tempResult.innerNode() && node()) {
398         if (HTMLMapElement* map = imageMap()) {
399             IntRect contentBox = contentBoxRect();
400             float zoom = style()->effectiveZoom();
401             int mapX = lroundf((x - tx - this->x() - contentBox.x()) / zoom);
402             int mapY = lroundf((y - ty - this->y() - contentBox.y()) / zoom);
403             if (map->mapMouseEvent(mapX, mapY, contentBox.size(), tempResult))
404                 tempResult.setInnerNonSharedNode(node());
405         }
406     }
407
408     if (!inside && result.isRectBasedTest())
409         result.append(tempResult);
410     if (inside)
411         result = tempResult;
412     return inside;
413 }
414
415 void RenderImage::updateAltText()
416 {
417     if (!node())
418         return;
419
420     if (node()->hasTagName(inputTag))
421         m_altText = static_cast<HTMLInputElement*>(node())->altText();
422     else if (node()->hasTagName(imgTag))
423         m_altText = static_cast<HTMLImageElement*>(node())->altText();
424 #if ENABLE(WML)
425     else if (node()->hasTagName(WMLNames::imgTag))
426         m_altText = static_cast<WMLImageElement*>(node())->altText();
427 #endif
428 }
429
430 bool RenderImage::isLogicalWidthSpecified() const
431 {
432     switch (style()->logicalWidth().type()) {
433         case Fixed:
434         case Percent:
435             return true;
436         case Auto:
437         case Relative: // FIXME: Shouldn't this case return true?
438         case Static:
439         case Intrinsic:
440         case MinIntrinsic:
441             return false;
442     }
443     ASSERT(false);
444     return false;
445 }
446
447 bool RenderImage::isLogicalHeightSpecified() const
448 {
449     switch (style()->logicalHeight().type()) {
450         case Fixed:
451         case Percent:
452             return true;
453         case Auto:
454         case Relative: // FIXME: Shouldn't this case return true?
455         case Static:
456         case Intrinsic:
457         case MinIntrinsic:
458             return false;
459     }
460     ASSERT(false);
461     return false;
462 }
463
464 int RenderImage::computeReplacedLogicalWidth(bool includeMaxWidth) const
465 {
466     if (m_imageResource->imageHasRelativeWidth())
467         if (RenderObject* cb = isPositioned() ? container() : containingBlock()) {
468             if (cb->isBox())
469                 m_imageResource->setImageContainerSize(IntSize(toRenderBox(cb)->availableWidth(), toRenderBox(cb)->availableHeight()));
470         }
471
472     int logicalWidth;
473     if (isLogicalWidthSpecified())
474         logicalWidth = computeReplacedLogicalWidthUsing(style()->logicalWidth());
475     else if (m_imageResource->usesImageContainerSize()) {
476         IntSize size = m_imageResource->imageSize(style()->effectiveZoom());
477         logicalWidth = style()->isHorizontalWritingMode() ? size.width() : size.height();
478     } else if (m_imageResource->imageHasRelativeWidth())
479         logicalWidth = 0; // If the image is relatively-sized, set the width to 0 until there is a set container size.
480     else
481         logicalWidth = calcAspectRatioLogicalWidth();
482
483     int minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
484     int maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
485
486     return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
487 }
488
489 int RenderImage::computeReplacedLogicalHeight() const
490 {
491     int logicalHeight;
492     if (isLogicalHeightSpecified())
493         logicalHeight = computeReplacedLogicalHeightUsing(style()->logicalHeight());
494     else if (m_imageResource->usesImageContainerSize()) {
495         IntSize size = m_imageResource->imageSize(style()->effectiveZoom());
496         logicalHeight = style()->isHorizontalWritingMode() ? size.height() : size.width();
497     } else if (m_imageResource->imageHasRelativeHeight())
498         logicalHeight = 0; // If the image is relatively-sized, set the height to 0 until there is a set container size.
499     else
500         logicalHeight = calcAspectRatioLogicalHeight();
501
502     int minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
503     int maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
504
505     return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
506 }
507
508 int RenderImage::calcAspectRatioLogicalWidth() const
509 {
510     int intrinsicWidth = intrinsicLogicalWidth();
511     int intrinsicHeight = intrinsicLogicalHeight();
512     if (!intrinsicHeight)
513         return 0;
514     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
515         return intrinsicWidth; // Don't bother scaling.
516     return RenderBox::computeReplacedLogicalHeight() * intrinsicWidth / intrinsicHeight;
517 }
518
519 int RenderImage::calcAspectRatioLogicalHeight() const
520 {
521     int intrinsicWidth = intrinsicLogicalWidth();
522     int intrinsicHeight = intrinsicLogicalHeight();
523     if (!intrinsicWidth)
524         return 0;
525     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
526         return intrinsicHeight; // Don't bother scaling.
527     return RenderBox::computeReplacedLogicalWidth() * intrinsicHeight / intrinsicWidth;
528 }
529
530 } // namespace WebCore