2010-11-30 Daniel Bates <dbates@rim.com>
[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         RenderStyle* styleToUse = areaElement->computedStyle();
362         paintInfo.context->drawFocusRing(areaElement->getPath(this), styleToUse->outlineWidth(), styleToUse->outlineOffset(), styleToUse->visitedDependentColor(CSSPropertyOutlineColor));
363         break;
364     }
365 }
366     
367 void RenderImage::paintIntoRect(GraphicsContext* context, const IntRect& rect)
368 {
369     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || rect.width() <= 0 || rect.height() <= 0)
370         return;
371
372     Image* img = m_imageResource->image(rect.width(), rect.height());
373     if (!img || img->isNull())
374         return;
375
376     HTMLImageElement* imageElt = (node() && node()->hasTagName(imgTag)) ? static_cast<HTMLImageElement*>(node()) : 0;
377     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
378     bool useLowQualityScaling = shouldPaintAtLowQuality(context, m_imageResource->image(), 0, rect.size());
379     context->drawImage(m_imageResource->image(rect.width(), rect.height()), style()->colorSpace(), rect, compositeOperator, useLowQualityScaling);
380 }
381
382 int RenderImage::minimumReplacedHeight() const
383 {
384     return m_imageResource->errorOccurred() ? intrinsicSize().height() : 0;
385 }
386
387 HTMLMapElement* RenderImage::imageMap() const
388 {
389     HTMLImageElement* i = node() && node()->hasTagName(imgTag) ? static_cast<HTMLImageElement*>(node()) : 0;
390     return i ? i->document()->getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
391 }
392
393 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty, HitTestAction hitTestAction)
394 {
395     HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
396     bool inside = RenderReplaced::nodeAtPoint(request, tempResult, x, y, tx, ty, hitTestAction);
397
398     if (tempResult.innerNode() && node()) {
399         if (HTMLMapElement* map = imageMap()) {
400             IntRect contentBox = contentBoxRect();
401             float zoom = style()->effectiveZoom();
402             int mapX = lroundf((x - tx - this->x() - contentBox.x()) / zoom);
403             int mapY = lroundf((y - ty - this->y() - contentBox.y()) / zoom);
404             if (map->mapMouseEvent(mapX, mapY, contentBox.size(), tempResult))
405                 tempResult.setInnerNonSharedNode(node());
406         }
407     }
408
409     if (!inside && result.isRectBasedTest())
410         result.append(tempResult);
411     if (inside)
412         result = tempResult;
413     return inside;
414 }
415
416 void RenderImage::updateAltText()
417 {
418     if (!node())
419         return;
420
421     if (node()->hasTagName(inputTag))
422         m_altText = static_cast<HTMLInputElement*>(node())->altText();
423     else if (node()->hasTagName(imgTag))
424         m_altText = static_cast<HTMLImageElement*>(node())->altText();
425 #if ENABLE(WML)
426     else if (node()->hasTagName(WMLNames::imgTag))
427         m_altText = static_cast<WMLImageElement*>(node())->altText();
428 #endif
429 }
430
431 bool RenderImage::isLogicalWidthSpecified() const
432 {
433     switch (style()->logicalWidth().type()) {
434         case Fixed:
435         case Percent:
436             return true;
437         case Auto:
438         case Relative: // FIXME: Shouldn't this case return true?
439         case Static:
440         case Intrinsic:
441         case MinIntrinsic:
442             return false;
443     }
444     ASSERT(false);
445     return false;
446 }
447
448 bool RenderImage::isLogicalHeightSpecified() const
449 {
450     switch (style()->logicalHeight().type()) {
451         case Fixed:
452         case Percent:
453             return true;
454         case Auto:
455         case Relative: // FIXME: Shouldn't this case return true?
456         case Static:
457         case Intrinsic:
458         case MinIntrinsic:
459             return false;
460     }
461     ASSERT(false);
462     return false;
463 }
464
465 int RenderImage::computeReplacedLogicalWidth(bool includeMaxWidth) const
466 {
467     if (m_imageResource->imageHasRelativeWidth())
468         if (RenderObject* cb = isPositioned() ? container() : containingBlock()) {
469             if (cb->isBox())
470                 m_imageResource->setImageContainerSize(IntSize(toRenderBox(cb)->availableWidth(), toRenderBox(cb)->availableHeight()));
471         }
472
473     int logicalWidth;
474     if (isLogicalWidthSpecified())
475         logicalWidth = computeReplacedLogicalWidthUsing(style()->logicalWidth());
476     else if (m_imageResource->usesImageContainerSize()) {
477         IntSize size = m_imageResource->imageSize(style()->effectiveZoom());
478         logicalWidth = style()->isHorizontalWritingMode() ? size.width() : size.height();
479     } else if (m_imageResource->imageHasRelativeWidth())
480         logicalWidth = 0; // If the image is relatively-sized, set the width to 0 until there is a set container size.
481     else
482         logicalWidth = calcAspectRatioLogicalWidth();
483
484     int minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
485     int maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
486
487     return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
488 }
489
490 int RenderImage::computeReplacedLogicalHeight() const
491 {
492     int logicalHeight;
493     if (isLogicalHeightSpecified())
494         logicalHeight = computeReplacedLogicalHeightUsing(style()->logicalHeight());
495     else if (m_imageResource->usesImageContainerSize()) {
496         IntSize size = m_imageResource->imageSize(style()->effectiveZoom());
497         logicalHeight = style()->isHorizontalWritingMode() ? size.height() : size.width();
498     } else if (m_imageResource->imageHasRelativeHeight())
499         logicalHeight = 0; // If the image is relatively-sized, set the height to 0 until there is a set container size.
500     else
501         logicalHeight = calcAspectRatioLogicalHeight();
502
503     int minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
504     int maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
505
506     return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
507 }
508
509 int RenderImage::calcAspectRatioLogicalWidth() const
510 {
511     int intrinsicWidth = intrinsicLogicalWidth();
512     int intrinsicHeight = intrinsicLogicalHeight();
513     if (!intrinsicHeight)
514         return 0;
515     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
516         return intrinsicWidth; // Don't bother scaling.
517     return RenderBox::computeReplacedLogicalHeight() * intrinsicWidth / intrinsicHeight;
518 }
519
520 int RenderImage::calcAspectRatioLogicalHeight() const
521 {
522     int intrinsicWidth = intrinsicLogicalWidth();
523     int intrinsicHeight = intrinsicLogicalHeight();
524     if (!intrinsicWidth)
525         return 0;
526     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
527         return intrinsicHeight; // Don't bother scaling.
528     return RenderBox::computeReplacedLogicalWidth() * intrinsicHeight / intrinsicWidth;
529 }
530
531 } // namespace WebCore