#include "config.h"
#include "RenderImage.h"
#include "BitmapImage.h"
#include "FontCache.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "GraphicsContext.h"
#include "HTMLAreaElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLMapElement.h"
#include "HTMLNames.h"
#include "HitTestResult.h"
#include "Page.h"
#include "PaintInfo.h"
#include "RenderView.h"
#include "SVGImage.h"
#include <wtf/UnusedParam.h>
using namespace std;
namespace WebCore {
using namespace HTMLNames;
RenderImage::RenderImage(Node* node)
: RenderReplaced(node, IntSize())
, m_needsToSetSizeForAltText(false)
, m_didIncrementVisuallyNonEmptyPixelCount(false)
, m_isGeneratedContent(false)
{
updateAltText();
}
RenderImage::~RenderImage()
{
ASSERT(m_imageResource);
m_imageResource->shutdown();
}
void RenderImage::setImageResource(PassOwnPtr<RenderImageResource> imageResource)
{
ASSERT(!m_imageResource);
m_imageResource = imageResource;
m_imageResource->initialize(this);
}
static const unsigned short paddingWidth = 4;
static const unsigned short paddingHeight = 4;
static const float maxAltTextWidth = 1024;
static const int maxAltTextHeight = 256;
IntSize RenderImage::imageSizeForError(CachedImage* newImage) const
{
ASSERT_ARG(newImage, newImage);
ASSERT_ARG(newImage, newImage->imageForRenderer(this));
IntSize imageSize;
if (newImage->willPaintBrokenImage()) {
float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
pair<Image*, float> brokenImageAndImageScaleFactor = newImage->brokenImage(deviceScaleFactor);
imageSize = brokenImageAndImageScaleFactor.first->size();
imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
} else
imageSize = newImage->imageForRenderer(this)->size();
return IntSize(paddingWidth + imageSize.width() * style()->effectiveZoom(), paddingHeight + imageSize.height() * style()->effectiveZoom());
}
bool RenderImage::setImageSizeForAltText(CachedImage* newImage )
{
IntSize imageSize;
if (newImage && newImage->imageForRenderer(this))
imageSize = imageSizeForError(newImage);
else if (!m_altText.isEmpty() || newImage) {
imageSize = IntSize(paddingWidth, paddingHeight);
}
if (!m_altText.isEmpty()) {
FontCachePurgePreventer fontCachePurgePreventer;
const Font& font = style()->font();
IntSize textSize(min(font.width(RenderBlock::constructTextRun(this, font, m_altText, style())), maxAltTextWidth), min(font.fontMetrics().height(), maxAltTextHeight));
imageSize = imageSize.expandedTo(textSize);
}
if (imageSize == intrinsicSize())
return false;
setIntrinsicSize(imageSize);
return true;
}
void RenderImage::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderReplaced::styleDidChange(diff, oldStyle);
if (m_needsToSetSizeForAltText) {
if (!m_altText.isEmpty() && setImageSizeForAltText(m_imageResource->cachedImage()))
imageDimensionsChanged(true );
m_needsToSetSizeForAltText = false;
}
}
void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
{
if (documentBeingDestroyed() || document()->inPageCache())
return;
if (hasBoxDecorations() || hasMask())
RenderReplaced::imageChanged(newImage, rect);
if (!m_imageResource)
return;
if (newImage != m_imageResource->imagePtr() || !newImage)
return;
if (!m_didIncrementVisuallyNonEmptyPixelCount) {
view()->frameView()->incrementVisuallyNonEmptyPixelCount(m_imageResource->imageSize(1.0f));
m_didIncrementVisuallyNonEmptyPixelCount = true;
}
bool imageSizeChanged = false;
if (m_imageResource->errorOccurred()) {
if (!m_altText.isEmpty() && document()->isPendingStyleRecalc()) {
ASSERT(node());
if (node()) {
m_needsToSetSizeForAltText = true;
node()->setNeedsStyleRecalc(SyntheticStyleChange);
}
return;
}
imageSizeChanged = setImageSizeForAltText(m_imageResource->cachedImage());
}
imageDimensionsChanged(imageSizeChanged, rect);
}
bool RenderImage::updateIntrinsicSizeIfNeeded(const IntSize& newSize, bool imageSizeChanged)
{
if (newSize == intrinsicSize() && !imageSizeChanged)
return false;
if (m_imageResource->errorOccurred())
return imageSizeChanged;
setIntrinsicSize(newSize);
return true;
}
void RenderImage::imageDimensionsChanged(bool imageSizeChanged, const IntRect* rect)
{
bool shouldRepaint = true;
if (updateIntrinsicSizeIfNeeded(m_imageResource->imageSize(style()->effectiveZoom()), imageSizeChanged)) {
if (containingBlock()) {
int oldwidth = width();
int oldheight = height();
if (!preferredLogicalWidthsDirty())
setPreferredLogicalWidthsDirty(true);
computeLogicalWidth();
computeLogicalHeight();
if (imageSizeChanged || width() != oldwidth || height() != oldheight) {
shouldRepaint = false;
if (!selfNeedsLayout())
setNeedsLayout(true);
}
setWidth(oldwidth);
setHeight(oldheight);
}
}
if (shouldRepaint) {
LayoutRect repaintRect;
if (rect) {
repaintRect = enclosingIntRect(mapRect(*rect, FloatRect(FloatPoint(), m_imageResource->imageSize(1.0f)), contentBoxRect()));
repaintRect.intersect(contentBoxRect());
} else
repaintRect = contentBoxRect();
repaintRectangle(repaintRect);
#if USE(ACCELERATED_COMPOSITING)
contentChanged(ImageChanged);
#endif
}
}
void RenderImage::notifyFinished(CachedResource* newImage)
{
if (!m_imageResource)
return;
if (documentBeingDestroyed())
return;
#if USE(ACCELERATED_COMPOSITING)
if (newImage == m_imageResource->cachedImage()) {
contentChanged(ImageChanged);
}
#else
UNUSED_PARAM(newImage);
#endif
}
void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
LayoutUnit cWidth = contentWidth();
LayoutUnit cHeight = contentHeight();
LayoutUnit leftBorder = borderLeft();
LayoutUnit topBorder = borderTop();
LayoutUnit leftPad = paddingLeft();
LayoutUnit topPad = paddingTop();
GraphicsContext* context = paintInfo.context;
Page* page = 0;
if (Frame* frame = this->frame())
page = frame->page();
if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
if (paintInfo.phase == PaintPhaseSelection)
return;
if (page && paintInfo.phase == PaintPhaseForeground)
page->addRelevantUnpaintedObject(this, visualOverflowRect());
if (cWidth > 2 && cHeight > 2) {
context->setStrokeStyle(SolidStroke);
context->setStrokeColor(Color::lightGray, style()->colorSpace());
context->setFillColor(Color::transparent, style()->colorSpace());
context->drawRect(pixelSnappedIntRect(LayoutRect(paintOffset.x() + leftBorder + leftPad, paintOffset.y() + topBorder + topPad, cWidth, cHeight)));
bool errorPictureDrawn = false;
LayoutSize imageOffset;
LayoutUnit usableWidth = cWidth - 2;
LayoutUnit usableHeight = cHeight - 2;
RefPtr<Image> image = m_imageResource->image();
if (m_imageResource->errorOccurred() && !image->isNull() && usableWidth >= image->width() && usableHeight >= image->height()) {
float deviceScaleFactor = WebCore::deviceScaleFactor(frame());
pair<Image*, float> brokenImageAndImageScaleFactor = m_imageResource->cachedImage()->brokenImage(deviceScaleFactor);
image = brokenImageAndImageScaleFactor.first;
IntSize imageSize = image->size();
imageSize.scale(1 / brokenImageAndImageScaleFactor.second);
LayoutUnit centerX = (usableWidth - imageSize.width()) / 2;
if (centerX < 0)
centerX = 0;
LayoutUnit centerY = (usableHeight - imageSize.height()) / 2;
if (centerY < 0)
centerY = 0;
imageOffset = LayoutSize(leftBorder + leftPad + centerX + 1, topBorder + topPad + centerY + 1);
context->drawImage(image.get(), style()->colorSpace(), IntRect(roundedIntPoint(paintOffset + imageOffset), imageSize), CompositeSourceOver, shouldRespectImageOrientation());
errorPictureDrawn = true;
}
if (!m_altText.isEmpty()) {
String text = document()->displayStringModifiedByEncoding(m_altText);
context->setFillColor(style()->visitedDependentColor(CSSPropertyColor), style()->colorSpace());
const Font& font = style()->font();
const FontMetrics& fontMetrics = font.fontMetrics();
LayoutUnit ascent = fontMetrics.ascent();
LayoutPoint altTextOffset = paintOffset;
altTextOffset.move(leftBorder + leftPad, topBorder + topPad + ascent);
TextRun textRun = RenderBlock::constructTextRun(this, font, text, style());
LayoutUnit textWidth = font.width(textRun);
if (errorPictureDrawn) {
if (usableWidth >= textWidth && fontMetrics.height() <= imageOffset.height())
context->drawText(font, textRun, altTextOffset);
} else if (usableWidth >= textWidth && cHeight >= fontMetrics.height())
context->drawText(font, textRun, altTextOffset);
}
}
} else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
RefPtr<Image> img = m_imageResource->image(cWidth, cHeight);
if (!img || img->isNull()) {
if (page && paintInfo.phase == PaintPhaseForeground)
page->addRelevantUnpaintedObject(this, visualOverflowRect());
return;
}
#if PLATFORM(MAC)
if (style()->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
paintCustomHighlight(toPoint(paintOffset - location()), style()->highlight(), true);
#endif
LayoutSize contentSize(cWidth, cHeight);
LayoutPoint contentLocation = paintOffset;
contentLocation.move(leftBorder + leftPad, topBorder + topPad);
paintIntoRect(context, LayoutRect(contentLocation, contentSize));
if (cachedImage() && page && paintInfo.phase == PaintPhaseForeground) {
if (cachedImage()->isLoading())
page->addRelevantUnpaintedObject(this, LayoutRect(contentLocation, contentSize));
else
page->addRelevantRepaintedObject(this, LayoutRect(contentLocation, contentSize));
}
}
}
void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
RenderReplaced::paint(paintInfo, paintOffset);
if (paintInfo.phase == PaintPhaseOutline)
paintAreaElementFocusRing(paintInfo);
}
void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo)
{
Document* document = this->document();
if (document->printing() || !document->frame()->selection()->isFocusedAndActive())
return;
if (paintInfo.context->paintingDisabled() && !paintInfo.context->updatingControlTints())
return;
Node* focusedNode = document->focusedNode();
if (!focusedNode || !focusedNode->hasTagName(areaTag))
return;
HTMLAreaElement* areaElement = static_cast<HTMLAreaElement*>(focusedNode);
if (areaElement->imageElement() != node())
return;
Path path = areaElement->computePath(this);
if (path.isEmpty())
return;
RenderStyle* areaElementStyle = areaElement->computedStyle();
unsigned short outlineWidth = areaElementStyle->outlineWidth();
if (!outlineWidth)
return;
paintInfo.context->drawFocusRing(path, outlineWidth,
areaElementStyle->outlineOffset(),
areaElementStyle->visitedDependentColor(CSSPropertyOutlineColor));
}
void RenderImage::areaElementFocusChanged(HTMLAreaElement* element)
{
ASSERT_UNUSED(element, element->imageElement() == node());
repaint();
}
void RenderImage::paintIntoRect(GraphicsContext* context, const LayoutRect& rect)
{
IntRect alignedRect = pixelSnappedIntRect(rect);
if (!m_imageResource->hasImage() || m_imageResource->errorOccurred() || alignedRect.width() <= 0 || alignedRect.height() <= 0)
return;
RefPtr<Image> img = m_imageResource->image(alignedRect.width(), alignedRect.height());
if (!img || img->isNull())
return;
HTMLImageElement* imageElt = (node() && node()->hasTagName(imgTag)) ? static_cast<HTMLImageElement*>(node()) : 0;
CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
Image* image = m_imageResource->image().get();
bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, alignedRect.size());
context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), style()->colorSpace(), alignedRect, compositeOperator, shouldRespectImageOrientation(), useLowQualityScaling);
}
bool RenderImage::backgroundIsObscured() const
{
if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
return false;
if (m_imageResource->cachedImage() && !m_imageResource->cachedImage()->isLoaded())
return false;
EFillBox backgroundClip = style()->backgroundClip();
if (backgroundClip == BorderFillBox && style()->hasBorder() && !borderObscuresBackground())
return false;
if ((backgroundClip == BorderFillBox || backgroundClip == PaddingFillBox) && style()->hasPadding())
return false;
Image* image = m_imageResource->image().get();
if (!image || !image->isBitmapImage() || image->currentFrameHasAlpha())
return false;
return true;
}
int RenderImage::minimumReplacedHeight() const
{
return m_imageResource->errorOccurred() ? intrinsicSize().height() : 0;
}
HTMLMapElement* RenderImage::imageMap() const
{
HTMLImageElement* i = node() && node()->hasTagName(imgTag) ? static_cast<HTMLImageElement*>(node()) : 0;
return i ? i->treeScope()->getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
}
bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding(), result.shadowContentFilterPolicy());
bool inside = RenderReplaced::nodeAtPoint(request, tempResult, pointInContainer, accumulatedOffset, hitTestAction);
if (tempResult.innerNode() && node()) {
if (HTMLMapElement* map = imageMap()) {
LayoutRect contentBox = contentBoxRect();
float scaleFactor = 1 / style()->effectiveZoom();
LayoutPoint mapLocation(pointInContainer.x() - accumulatedOffset.x() - this->x() - contentBox.x(), pointInContainer.y() - accumulatedOffset.y() - this->y() - contentBox.y());
mapLocation.scale(scaleFactor, scaleFactor);
if (map->mapMouseEvent(mapLocation, contentBox.size(), tempResult))
tempResult.setInnerNonSharedNode(node());
}
}
if (!inside && result.isRectBasedTest())
result.append(tempResult);
if (inside)
result = tempResult;
return inside;
}
void RenderImage::updateAltText()
{
if (!node())
return;
if (node()->hasTagName(inputTag))
m_altText = static_cast<HTMLInputElement*>(node())->altText();
else if (node()->hasTagName(imgTag))
m_altText = static_cast<HTMLImageElement*>(node())->altText();
}
void RenderImage::layout()
{
RenderReplaced::layout();
IntSize containerSize(contentWidth(), contentHeight());
if (!containerSize.isEmpty())
m_imageResource->setContainerSizeForRenderer(containerSize);
}
void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
{
RenderReplaced::computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio, isPercentageIntrinsicSize);
if (intrinsicSize.isEmpty() && (m_imageResource->imageHasRelativeWidth() || m_imageResource->imageHasRelativeHeight())) {
RenderObject* containingBlock = isPositioned() ? container() : this->containingBlock();
if (containingBlock->isBox()) {
RenderBox* box = toRenderBox(containingBlock);
intrinsicSize.setWidth(box->availableLogicalWidth());
intrinsicSize.setHeight(box->availableLogicalHeight());
}
}
if (m_imageResource && m_imageResource->errorOccurred()) {
intrinsicRatio = 1;
return;
}
}
bool RenderImage::needsPreferredWidthsRecalculation() const
{
if (RenderReplaced::needsPreferredWidthsRecalculation())
return true;
return embeddedContentBox();
}
RenderBox* RenderImage::embeddedContentBox() const
{
if (!m_imageResource)
return 0;
#if ENABLE(SVG)
CachedImage* cachedImage = m_imageResource->cachedImage();
if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
return static_cast<SVGImage*>(cachedImage->image())->embeddedContentBox();
#endif
return 0;
}
}