2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2000 Dirk Mueller (mueller@kde.org)
4 * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
5 * Copyright (C) Research In Motion Limited 2011-2012. All rights reserved.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
25 #include "core/rendering/RenderReplaced.h"
27 #include "core/editing/PositionWithAffinity.h"
28 #include "core/paint/ReplacedPainter.h"
29 #include "core/rendering/GraphicsContextAnnotator.h"
30 #include "core/rendering/RenderBlock.h"
31 #include "core/rendering/RenderImage.h"
32 #include "core/rendering/RenderLayer.h"
33 #include "core/rendering/RenderView.h"
34 #include "platform/LengthFunctions.h"
35 #include "platform/graphics/GraphicsContext.h"
39 const int RenderReplaced::defaultWidth = 300;
40 const int RenderReplaced::defaultHeight = 150;
42 RenderReplaced::RenderReplaced(Element* element)
44 , m_intrinsicSize(defaultWidth, defaultHeight)
49 RenderReplaced::RenderReplaced(Element* element, const LayoutSize& intrinsicSize)
51 , m_intrinsicSize(intrinsicSize)
56 RenderReplaced::~RenderReplaced()
60 void RenderReplaced::willBeDestroyed()
62 if (!documentBeingDestroyed() && parent())
63 parent()->dirtyLinesFromChangedChild(this);
65 RenderBox::willBeDestroyed();
68 void RenderReplaced::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
70 RenderBox::styleDidChange(diff, oldStyle);
72 bool hadStyle = (oldStyle != 0);
73 float oldZoom = hadStyle ? oldStyle->effectiveZoom() : RenderStyle::initialZoom();
74 if (style() && style()->effectiveZoom() != oldZoom)
75 intrinsicSizeChanged();
78 void RenderReplaced::layout()
80 ASSERT(needsLayout());
82 LayoutRect oldContentRect = replacedContentRect();
84 setHeight(minimumReplacedHeight());
87 updateLogicalHeight();
90 addVisualEffectOverflow();
91 updateLayerTransformAfterLayout();
92 invalidateBackgroundObscurationStatus();
96 if (replacedContentRect() != oldContentRect)
97 setShouldDoFullPaintInvalidation();
100 void RenderReplaced::intrinsicSizeChanged()
102 int scaledWidth = static_cast<int>(defaultWidth * style()->effectiveZoom());
103 int scaledHeight = static_cast<int>(defaultHeight * style()->effectiveZoom());
104 m_intrinsicSize = IntSize(scaledWidth, scaledHeight);
105 setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
108 void RenderReplaced::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
110 ReplacedPainter(*this).paint(paintInfo, paintOffset);
113 bool RenderReplaced::shouldPaint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
115 if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseOutline && paintInfo.phase != PaintPhaseSelfOutline
116 && paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseMask && paintInfo.phase != PaintPhaseClippingMask)
119 if (!paintInfo.shouldPaintWithinRoot(this))
122 // if we're invisible or haven't received a layout yet, then just bail.
123 if (style()->visibility() != VISIBLE)
126 LayoutPoint adjustedPaintOffset = paintOffset + location();
128 // Early exit if the element touches the edges.
129 LayoutUnit top = adjustedPaintOffset.y() + visualOverflowRect().y();
130 LayoutUnit bottom = adjustedPaintOffset.y() + visualOverflowRect().maxY();
131 if (isSelected() && inlineBoxWrapper()) {
132 LayoutUnit selTop = paintOffset.y() + inlineBoxWrapper()->root().selectionTop();
133 LayoutUnit selBottom = paintOffset.y() + selTop + inlineBoxWrapper()->root().selectionHeight();
134 top = std::min(selTop, top);
135 bottom = std::max(selBottom, bottom);
138 if (adjustedPaintOffset.x() + visualOverflowRect().x() >= paintInfo.rect.maxX() || adjustedPaintOffset.x() + visualOverflowRect().maxX() <= paintInfo.rect.x())
141 if (top >= paintInfo.rect.maxY() || bottom <= paintInfo.rect.y())
147 bool RenderReplaced::hasReplacedLogicalHeight() const
149 if (style()->logicalHeight().isAuto())
152 if (style()->logicalHeight().isSpecified()) {
153 if (hasAutoHeightOrContainingBlockWithAutoHeight())
158 if (style()->logicalHeight().isIntrinsic())
164 bool RenderReplaced::needsPreferredWidthsRecalculation() const
166 // If the height is a percentage and the width is auto, then the containingBlocks's height changing can cause
167 // this node to change it's preferred width because it maintains aspect ratio.
168 return hasRelativeLogicalHeight() && style()->logicalWidth().isAuto() && !hasAutoHeightOrContainingBlockWithAutoHeight();
171 static inline bool rendererHasAspectRatio(const RenderObject* renderer)
174 return renderer->isImage() || renderer->isCanvas() || renderer->isVideo();
177 void RenderReplaced::computeAspectRatioInformationForRenderBox(RenderBox* contentRenderer, FloatSize& constrainedSize, double& intrinsicRatio) const
179 FloatSize intrinsicSize;
180 if (contentRenderer) {
181 contentRenderer->computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
183 // Handle zoom & vertical writing modes here, as the embedded document doesn't know about them.
184 intrinsicSize.scale(style()->effectiveZoom());
186 intrinsicSize.scale(toRenderImage(this)->imageDevicePixelRatio());
188 // Update our intrinsic size to match what the content renderer has computed, so that when we
189 // constrain the size below, the correct intrinsic size will be obtained for comparison against
190 // min and max widths.
191 if (intrinsicRatio && !intrinsicSize.isEmpty())
192 m_intrinsicSize = LayoutSize(intrinsicSize);
194 if (!isHorizontalWritingMode()) {
196 intrinsicRatio = 1 / intrinsicRatio;
197 intrinsicSize = intrinsicSize.transposedSize();
200 computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
201 if (intrinsicRatio && !intrinsicSize.isEmpty())
202 m_intrinsicSize = LayoutSize(isHorizontalWritingMode() ? intrinsicSize : intrinsicSize.transposedSize());
205 // Now constrain the intrinsic size along each axis according to minimum and maximum width/heights along the
206 // opposite axis. So for example a maximum width that shrinks our width will result in the height we compute here
207 // having to shrink in order to preserve the aspect ratio. Because we compute these values independently along
208 // each axis, the final returned size may in fact not preserve the aspect ratio.
209 // FIXME: In the long term, it might be better to just return this code more to the way it used to be before this
210 // function was added, since all it has done is make the code more unclear.
211 constrainedSize = intrinsicSize;
212 if (intrinsicRatio && !intrinsicSize.isEmpty() && style()->logicalWidth().isAuto() && style()->logicalHeight().isAuto()) {
213 // We can't multiply or divide by 'intrinsicRatio' here, it breaks tests, like fast/images/zoomed-img-size.html, which
214 // can only be fixed once subpixel precision is available for things like intrinsicWidth/Height - which include zoom!
215 constrainedSize.setWidth(RenderBox::computeReplacedLogicalHeight() * intrinsicSize.width() / intrinsicSize.height());
216 constrainedSize.setHeight(RenderBox::computeReplacedLogicalWidth() * intrinsicSize.height() / intrinsicSize.width());
220 LayoutRect RenderReplaced::replacedContentRect(const LayoutSize* overriddenIntrinsicSize) const
222 LayoutRect contentRect = contentBoxRect();
223 ObjectFit objectFit = style()->objectFit();
225 if (objectFit == ObjectFitFill && style()->objectPosition() == RenderStyle::initialObjectPosition()) {
229 LayoutSize intrinsicSize = overriddenIntrinsicSize ? *overriddenIntrinsicSize : this->intrinsicSize();
230 if (!intrinsicSize.width() || !intrinsicSize.height())
233 LayoutRect finalRect = contentRect;
235 case ObjectFitContain:
236 case ObjectFitScaleDown:
238 finalRect.setSize(finalRect.size().fitToAspectRatio(intrinsicSize, objectFit == ObjectFitCover ? AspectRatioFitGrow : AspectRatioFitShrink));
239 if (objectFit != ObjectFitScaleDown || finalRect.width() <= intrinsicSize.width())
243 finalRect.setSize(intrinsicSize);
248 ASSERT_NOT_REACHED();
251 LayoutUnit xOffset = minimumValueForLength(style()->objectPosition().x(), contentRect.width() - finalRect.width());
252 LayoutUnit yOffset = minimumValueForLength(style()->objectPosition().y(), contentRect.height() - finalRect.height());
253 finalRect.move(xOffset, yOffset);
258 void RenderReplaced::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
260 // If there's an embeddedContentBox() of a remote, referenced document available, this code-path should never be used.
261 ASSERT(!embeddedContentBox());
262 intrinsicSize = FloatSize(intrinsicLogicalWidth().toFloat(), intrinsicLogicalHeight().toFloat());
264 // Figure out if we need to compute an intrinsic ratio.
265 if (intrinsicSize.isEmpty() || !rendererHasAspectRatio(this))
268 intrinsicRatio = intrinsicSize.width() / intrinsicSize.height();
271 LayoutUnit RenderReplaced::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
273 if (style()->logicalWidth().isSpecified() || style()->logicalWidth().isIntrinsic())
274 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
276 RenderBox* contentRenderer = embeddedContentBox();
278 // 10.3.2 Inline, replaced elements: http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width
279 double intrinsicRatio = 0;
280 FloatSize constrainedSize;
281 computeAspectRatioInformationForRenderBox(contentRenderer, constrainedSize, intrinsicRatio);
283 if (style()->logicalWidth().isAuto()) {
284 bool computedHeightIsAuto = hasAutoHeightOrContainingBlockWithAutoHeight();
285 bool hasIntrinsicWidth = constrainedSize.width() > 0;
287 // If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic width, then that intrinsic width is the used value of 'width'.
288 if (computedHeightIsAuto && hasIntrinsicWidth)
289 return computeReplacedLogicalWidthRespectingMinMaxWidth(constrainedSize.width(), shouldComputePreferred);
291 bool hasIntrinsicHeight = constrainedSize.height() > 0;
292 if (intrinsicRatio) {
293 // If 'height' and 'width' both have computed values of 'auto' and the element has no intrinsic width, but does have an intrinsic height and intrinsic ratio;
294 // or if 'width' has a computed value of 'auto', 'height' has some other computed value, and the element does have an intrinsic ratio; then the used value
295 // of 'width' is: (used height) * (intrinsic ratio)
296 if (intrinsicRatio && ((computedHeightIsAuto && !hasIntrinsicWidth && hasIntrinsicHeight) || !computedHeightIsAuto)) {
297 LayoutUnit logicalHeight = computeReplacedLogicalHeight();
298 return computeReplacedLogicalWidthRespectingMinMaxWidth(roundToInt(round(logicalHeight * intrinsicRatio)), shouldComputePreferred);
301 // If 'height' and 'width' both have computed values of 'auto' and the element has an intrinsic ratio but no intrinsic height or width, then the used value of
302 // 'width' is undefined in CSS 2.1. However, it is suggested that, if the containing block's width does not itself depend on the replaced element's width, then
303 // the used value of 'width' is calculated from the constraint equation used for block-level, non-replaced elements in normal flow.
304 if (computedHeightIsAuto && !hasIntrinsicWidth && !hasIntrinsicHeight) {
305 if (shouldComputePreferred == ComputePreferred)
307 // The aforementioned 'constraint equation' used for block-level, non-replaced elements in normal flow:
308 // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
309 LayoutUnit logicalWidth = containingBlock()->availableLogicalWidth();
311 // This solves above equation for 'width' (== logicalWidth).
312 LayoutUnit marginStart = minimumValueForLength(style()->marginStart(), logicalWidth);
313 LayoutUnit marginEnd = minimumValueForLength(style()->marginEnd(), logicalWidth);
314 logicalWidth = std::max<LayoutUnit>(0, logicalWidth - (marginStart + marginEnd + (width() - clientWidth())));
315 return computeReplacedLogicalWidthRespectingMinMaxWidth(logicalWidth, shouldComputePreferred);
319 // Otherwise, if 'width' has a computed value of 'auto', and the element has an intrinsic width, then that intrinsic width is the used value of 'width'.
320 if (hasIntrinsicWidth)
321 return computeReplacedLogicalWidthRespectingMinMaxWidth(constrainedSize.width(), shouldComputePreferred);
323 // Otherwise, if 'width' has a computed value of 'auto', but none of the conditions above are met, then the used value of 'width' becomes 300px. If 300px is too
324 // wide to fit the device, UAs should use the width of the largest rectangle that has a 2:1 ratio and fits the device instead.
325 // Note: We fall through and instead return intrinsicLogicalWidth() here - to preserve existing WebKit behavior, which might or might not be correct, or desired.
326 // Changing this to return cDefaultWidth, will affect lots of test results. Eg. some tests assume that a blank <img> tag (which implies width/height=auto)
327 // has no intrinsic size, which is wrong per CSS 2.1, but matches our behavior since a long time.
330 return computeReplacedLogicalWidthRespectingMinMaxWidth(intrinsicLogicalWidth(), shouldComputePreferred);
333 LayoutUnit RenderReplaced::computeReplacedLogicalHeight() const
335 // 10.5 Content height: the 'height' property: http://www.w3.org/TR/CSS21/visudet.html#propdef-height
336 if (hasReplacedLogicalHeight())
337 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
339 RenderBox* contentRenderer = embeddedContentBox();
341 // 10.6.2 Inline, replaced elements: http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-height
342 double intrinsicRatio = 0;
343 FloatSize constrainedSize;
344 computeAspectRatioInformationForRenderBox(contentRenderer, constrainedSize, intrinsicRatio);
346 bool widthIsAuto = style()->logicalWidth().isAuto();
347 bool hasIntrinsicHeight = constrainedSize.height() > 0;
349 // If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic height, then that intrinsic height is the used value of 'height'.
350 if (widthIsAuto && hasIntrinsicHeight)
351 return computeReplacedLogicalHeightRespectingMinMaxHeight(constrainedSize.height());
353 // Otherwise, if 'height' has a computed value of 'auto', and the element has an intrinsic ratio then the used value of 'height' is:
354 // (used width) / (intrinsic ratio)
356 return computeReplacedLogicalHeightRespectingMinMaxHeight(roundToInt(round(availableLogicalWidth() / intrinsicRatio)));
358 // Otherwise, if 'height' has a computed value of 'auto', and the element has an intrinsic height, then that intrinsic height is the used value of 'height'.
359 if (hasIntrinsicHeight)
360 return computeReplacedLogicalHeightRespectingMinMaxHeight(constrainedSize.height());
362 // Otherwise, if 'height' has a computed value of 'auto', but none of the conditions above are met, then the used value of 'height' must be set to the height
363 // of the largest rectangle that has a 2:1 ratio, has a height not greater than 150px, and has a width not greater than the device width.
364 return computeReplacedLogicalHeightRespectingMinMaxHeight(intrinsicLogicalHeight());
367 void RenderReplaced::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
369 minLogicalWidth = maxLogicalWidth = intrinsicLogicalWidth();
372 void RenderReplaced::computePreferredLogicalWidths()
374 ASSERT(preferredLogicalWidthsDirty());
376 // We cannot resolve any percent logical width here as the available logical
377 // width may not be set on our containing block.
378 if (style()->logicalWidth().isPercent())
379 computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
381 m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = computeReplacedLogicalWidth(ComputePreferred);
383 RenderStyle* styleToUse = style();
384 if (styleToUse->logicalWidth().isPercent() || styleToUse->logicalMaxWidth().isPercent())
385 m_minPreferredLogicalWidth = 0;
387 if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
388 m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
389 m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
392 if (styleToUse->logicalMaxWidth().isFixed()) {
393 m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
394 m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
397 LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
398 m_minPreferredLogicalWidth += borderAndPadding;
399 m_maxPreferredLogicalWidth += borderAndPadding;
401 clearPreferredLogicalWidthsDirty();
404 PositionWithAffinity RenderReplaced::positionForPoint(const LayoutPoint& point)
406 // FIXME: This code is buggy if the replaced element is relative positioned.
407 InlineBox* box = inlineBoxWrapper();
408 RootInlineBox* rootBox = box ? &box->root() : 0;
410 LayoutUnit top = rootBox ? rootBox->selectionTop() : logicalTop();
411 LayoutUnit bottom = rootBox ? rootBox->selectionBottom() : logicalBottom();
413 LayoutUnit blockDirectionPosition = isHorizontalWritingMode() ? point.y() + y() : point.x() + x();
414 LayoutUnit lineDirectionPosition = isHorizontalWritingMode() ? point.x() + x() : point.y() + y();
416 if (blockDirectionPosition < top)
417 return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM); // coordinates are above
419 if (blockDirectionPosition >= bottom)
420 return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM); // coordinates are below
423 if (lineDirectionPosition <= logicalLeft() + (logicalWidth() / 2))
424 return createPositionWithAffinity(0, DOWNSTREAM);
425 return createPositionWithAffinity(1, DOWNSTREAM);
428 return RenderBox::positionForPoint(point);
431 LayoutRect RenderReplaced::selectionRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer) const
433 ASSERT(!needsLayout());
438 LayoutRect rect = localSelectionRect();
439 mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, 0);
443 LayoutRect RenderReplaced::localSelectionRect(bool checkWhetherSelected) const
445 if (checkWhetherSelected && !isSelected())
448 if (!inlineBoxWrapper())
449 // We're a block-level replaced element. Just return our own dimensions.
450 return LayoutRect(LayoutPoint(), size());
452 RootInlineBox& root = inlineBoxWrapper()->root();
453 LayoutUnit newLogicalTop = root.block().style()->slowIsFlippedBlocksWritingMode() ? inlineBoxWrapper()->logicalBottom() - root.selectionBottom() : root.selectionTop() - inlineBoxWrapper()->logicalTop();
454 if (root.block().style()->isHorizontalWritingMode())
455 return LayoutRect(0, newLogicalTop, width(), root.selectionHeight());
456 return LayoutRect(newLogicalTop, 0, root.selectionHeight(), height());
459 void RenderReplaced::setSelectionState(SelectionState state)
461 // The selection state for our containing block hierarchy is updated by the base class call.
462 RenderBox::setSelectionState(state);
464 if (!inlineBoxWrapper())
467 // We only include the space below the baseline in our layer's cached paint invalidation rect if the
468 // image is selected. Since the selection state has changed update the rect.
470 setPreviousPaintInvalidationRect(boundsRectForPaintInvalidation(containerForPaintInvalidation()));
472 if (canUpdateSelectionOnRootLineBoxes())
473 inlineBoxWrapper()->root().setHasSelectedChildren(isSelected());
476 bool RenderReplaced::isSelected() const
478 SelectionState s = selectionState();
479 if (s == SelectionNone)
481 if (s == SelectionInside)
484 int selectionStart, selectionEnd;
485 selectionStartEnd(selectionStart, selectionEnd);
486 if (s == SelectionStart)
487 return selectionStart == 0;
489 int end = node()->hasChildren() ? node()->countChildren() : 1;
490 if (s == SelectionEnd)
491 return selectionEnd == end;
492 if (s == SelectionBoth)
493 return selectionStart == 0 && selectionEnd == end;
498 LayoutRect RenderReplaced::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
500 if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
503 // The selectionRect can project outside of the overflowRect, so take their union
504 // for paint invalidation to avoid selection painting glitches.
505 LayoutRect r = isSelected() ? localSelectionRect() : visualOverflowRect();
506 mapRectToPaintInvalidationBacking(paintInvalidationContainer, r, paintInvalidationState);