Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderReplaced.cpp
1 /*
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.
6  *
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.
11  *
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.
16  *
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.
21  *
22  */
23
24 #include "config.h"
25 #include "core/rendering/RenderReplaced.h"
26
27 #include "RuntimeEnabledFeatures.h"
28 #include "core/rendering/GraphicsContextAnnotator.h"
29 #include "core/rendering/LayoutRepainter.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"
36
37 using namespace std;
38
39 namespace WebCore {
40
41 const int cDefaultWidth = 300;
42 const int cDefaultHeight = 150;
43
44 RenderReplaced::RenderReplaced(Element* element)
45     : RenderBox(element)
46     , m_intrinsicSize(cDefaultWidth, cDefaultHeight)
47 {
48     setReplaced(true);
49 }
50
51 RenderReplaced::RenderReplaced(Element* element, const LayoutSize& intrinsicSize)
52     : RenderBox(element)
53     , m_intrinsicSize(intrinsicSize)
54 {
55     setReplaced(true);
56 }
57
58 RenderReplaced::~RenderReplaced()
59 {
60 }
61
62 void RenderReplaced::willBeDestroyed()
63 {
64     if (!documentBeingDestroyed() && parent())
65         parent()->dirtyLinesFromChangedChild(this);
66
67     RenderBox::willBeDestroyed();
68 }
69
70 void RenderReplaced::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
71 {
72     RenderBox::styleDidChange(diff, oldStyle);
73
74     bool hadStyle = (oldStyle != 0);
75     float oldZoom = hadStyle ? oldStyle->effectiveZoom() : RenderStyle::initialZoom();
76     if (style() && style()->effectiveZoom() != oldZoom)
77         intrinsicSizeChanged();
78 }
79
80 void RenderReplaced::layout()
81 {
82     ASSERT(needsLayout());
83
84     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
85
86     setHeight(minimumReplacedHeight());
87
88     updateLogicalWidth();
89     updateLogicalHeight();
90
91     m_overflow.clear();
92     addVisualEffectOverflow();
93     updateLayerTransform();
94     invalidateBackgroundObscurationStatus();
95
96     repainter.repaintAfterLayout();
97     clearNeedsLayout();
98 }
99
100 void RenderReplaced::intrinsicSizeChanged()
101 {
102     int scaledWidth = static_cast<int>(cDefaultWidth * style()->effectiveZoom());
103     int scaledHeight = static_cast<int>(cDefaultHeight * style()->effectiveZoom());
104     m_intrinsicSize = IntSize(scaledWidth, scaledHeight);
105     setNeedsLayoutAndPrefWidthsRecalc();
106 }
107
108 void RenderReplaced::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
109 {
110     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
111
112     if (!shouldPaint(paintInfo, paintOffset))
113         return;
114
115     LayoutPoint adjustedPaintOffset = paintOffset + location();
116
117     if (hasBoxDecorations() && (paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection))
118         paintBoxDecorations(paintInfo, adjustedPaintOffset);
119
120     if (paintInfo.phase == PaintPhaseMask) {
121         paintMask(paintInfo, adjustedPaintOffset);
122         return;
123     }
124
125     if (paintInfo.phase == PaintPhaseClippingMask && (!hasLayer() || !layer()->hasCompositedClippingMask()))
126         return;
127
128     LayoutRect paintRect = LayoutRect(adjustedPaintOffset, size());
129     if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->outlineWidth())
130         paintOutline(paintInfo, paintRect);
131
132     if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection && !canHaveChildren() && paintInfo.phase != PaintPhaseClippingMask)
133         return;
134
135     if (!paintInfo.shouldPaintWithinRoot(this))
136         return;
137
138     bool drawSelectionTint = selectionState() != SelectionNone && !document().printing();
139     if (paintInfo.phase == PaintPhaseSelection) {
140         if (selectionState() == SelectionNone)
141             return;
142         drawSelectionTint = false;
143     }
144
145     bool completelyClippedOut = false;
146     if (style()->hasBorderRadius()) {
147         LayoutRect borderRect = LayoutRect(adjustedPaintOffset, size());
148
149         if (borderRect.isEmpty())
150             completelyClippedOut = true;
151         else {
152             // Push a clip if we have a border radius, since we want to round the foreground content that gets painted.
153             paintInfo.context->save();
154             RoundedRect roundedInnerRect = style()->getRoundedInnerBorderFor(paintRect,
155                 paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), true, true);
156             clipRoundedInnerRect(paintInfo.context, paintRect, roundedInnerRect);
157         }
158     }
159
160     if (!completelyClippedOut) {
161         if (paintInfo.phase == PaintPhaseClippingMask) {
162             paintClippingMask(paintInfo, adjustedPaintOffset);
163         } else {
164             paintReplaced(paintInfo, adjustedPaintOffset);
165         }
166
167         if (style()->hasBorderRadius())
168             paintInfo.context->restore();
169     }
170
171     // The selection tint never gets clipped by border-radius rounding, since we want it to run right up to the edges of
172     // surrounding content.
173     if (drawSelectionTint) {
174         LayoutRect selectionPaintingRect = localSelectionRect();
175         selectionPaintingRect.moveBy(adjustedPaintOffset);
176         paintInfo.context->fillRect(pixelSnappedIntRect(selectionPaintingRect), selectionBackgroundColor());
177     }
178 }
179
180 bool RenderReplaced::shouldPaint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
181 {
182     if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseOutline && paintInfo.phase != PaintPhaseSelfOutline
183         && paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseMask && paintInfo.phase != PaintPhaseClippingMask)
184         return false;
185
186     if (!paintInfo.shouldPaintWithinRoot(this))
187         return false;
188
189     // if we're invisible or haven't received a layout yet, then just bail.
190     if (style()->visibility() != VISIBLE)
191         return false;
192
193     LayoutPoint adjustedPaintOffset = paintOffset + location();
194
195     // Early exit if the element touches the edges.
196     LayoutUnit top = adjustedPaintOffset.y() + visualOverflowRect().y();
197     LayoutUnit bottom = adjustedPaintOffset.y() + visualOverflowRect().maxY();
198     if (isSelected() && inlineBoxWrapper()) {
199         LayoutUnit selTop = paintOffset.y() + inlineBoxWrapper()->root().selectionTop();
200         LayoutUnit selBottom = paintOffset.y() + selTop + inlineBoxWrapper()->root().selectionHeight();
201         top = min(selTop, top);
202         bottom = max(selBottom, bottom);
203     }
204
205     if (adjustedPaintOffset.x() + visualOverflowRect().x() >= paintInfo.rect.maxX() || adjustedPaintOffset.x() + visualOverflowRect().maxX() <= paintInfo.rect.x())
206         return false;
207
208     if (top >= paintInfo.rect.maxY() || bottom <= paintInfo.rect.y())
209         return false;
210
211     return true;
212 }
213
214 static inline RenderBlock* firstContainingBlockWithLogicalWidth(const RenderReplaced* replaced)
215 {
216     // We have to lookup the containing block, which has an explicit width, which must not be equal to our direct containing block.
217     // If the embedded document appears _after_ we performed the initial layout, our intrinsic size is 300x150. If our containing
218     // block doesn't provide an explicit width, it's set to the 300 default, coming from the initial layout run.
219     RenderBlock* containingBlock = replaced->containingBlock();
220     if (!containingBlock)
221         return 0;
222
223     for (; !containingBlock->isRenderView() && !containingBlock->isBody(); containingBlock = containingBlock->containingBlock()) {
224         if (containingBlock->style()->logicalWidth().isSpecified()
225             && containingBlock->style()->logicalMinWidth().isSpecified()
226             && (containingBlock->style()->logicalMaxWidth().isSpecified() || containingBlock->style()->logicalMaxWidth().isUndefined()))
227             return containingBlock;
228     }
229
230     return 0;
231 }
232
233 bool RenderReplaced::hasReplacedLogicalWidth() const
234 {
235     if (style()->logicalWidth().isSpecified())
236         return true;
237
238     if (style()->logicalWidth().isAuto())
239         return false;
240
241     return firstContainingBlockWithLogicalWidth(this);
242 }
243
244 bool RenderReplaced::hasReplacedLogicalHeight() const
245 {
246     if (style()->logicalHeight().isAuto())
247         return false;
248
249     if (style()->logicalHeight().isSpecified()) {
250         if (hasAutoHeightOrContainingBlockWithAutoHeight())
251             return false;
252         return true;
253     }
254
255     if (style()->logicalHeight().isIntrinsic())
256         return true;
257
258     return false;
259 }
260
261 bool RenderReplaced::needsPreferredWidthsRecalculation() const
262 {
263     // If the height is a percentage and the width is auto, then the containingBlocks's height changing can cause
264     // this node to change it's preferred width because it maintains aspect ratio.
265     return hasRelativeLogicalHeight() && style()->logicalWidth().isAuto() && !hasAutoHeightOrContainingBlockWithAutoHeight();
266 }
267
268 static inline bool rendererHasAspectRatio(const RenderObject* renderer)
269 {
270     ASSERT(renderer);
271     return renderer->isImage() || renderer->isCanvas() || renderer->isVideo();
272 }
273
274 void RenderReplaced::computeAspectRatioInformationForRenderBox(RenderBox* contentRenderer, FloatSize& constrainedSize, double& intrinsicRatio) const
275 {
276     FloatSize intrinsicSize;
277     if (contentRenderer) {
278         contentRenderer->computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
279
280         // Handle zoom & vertical writing modes here, as the embedded document doesn't know about them.
281         intrinsicSize.scale(style()->effectiveZoom());
282         if (isRenderImage())
283             intrinsicSize.scale(toRenderImage(this)->imageDevicePixelRatio());
284
285         // Update our intrinsic size to match what the content renderer has computed, so that when we
286         // constrain the size below, the correct intrinsic size will be obtained for comparison against
287         // min and max widths.
288         if (intrinsicRatio && !intrinsicSize.isEmpty())
289             m_intrinsicSize = LayoutSize(intrinsicSize);
290
291         if (!isHorizontalWritingMode()) {
292             if (intrinsicRatio)
293                 intrinsicRatio = 1 / intrinsicRatio;
294             intrinsicSize = intrinsicSize.transposedSize();
295         }
296     } else {
297         computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
298         if (intrinsicRatio && !intrinsicSize.isEmpty())
299             m_intrinsicSize = LayoutSize(isHorizontalWritingMode() ? intrinsicSize : intrinsicSize.transposedSize());
300     }
301
302     // Now constrain the intrinsic size along each axis according to minimum and maximum width/heights along the
303     // opposite axis. So for example a maximum width that shrinks our width will result in the height we compute here
304     // having to shrink in order to preserve the aspect ratio. Because we compute these values independently along
305     // each axis, the final returned size may in fact not preserve the aspect ratio.
306     // FIXME: In the long term, it might be better to just return this code more to the way it used to be before this
307     // function was added, since all it has done is make the code more unclear.
308     constrainedSize = intrinsicSize;
309     if (intrinsicRatio && !intrinsicSize.isEmpty() && style()->logicalWidth().isAuto() && style()->logicalHeight().isAuto()) {
310         // We can't multiply or divide by 'intrinsicRatio' here, it breaks tests, like fast/images/zoomed-img-size.html, which
311         // can only be fixed once subpixel precision is available for things like intrinsicWidth/Height - which include zoom!
312         constrainedSize.setWidth(RenderBox::computeReplacedLogicalHeight() * intrinsicSize.width() / intrinsicSize.height());
313         constrainedSize.setHeight(RenderBox::computeReplacedLogicalWidth() * intrinsicSize.height() / intrinsicSize.width());
314     }
315 }
316
317 LayoutRect RenderReplaced::replacedContentRect(const LayoutSize* overriddenIntrinsicSize) const
318 {
319     LayoutRect contentRect = contentBoxRect();
320     ObjectFit objectFit = style()->objectFit();
321
322     if (objectFit == ObjectFitFill && style()->objectPosition() == RenderStyle::initialObjectPosition()) {
323         if (!isVideo() || RuntimeEnabledFeatures::objectFitPositionEnabled())
324             return contentRect;
325         objectFit = ObjectFitContain;
326     }
327
328     LayoutSize intrinsicSize = overriddenIntrinsicSize ? *overriddenIntrinsicSize : this->intrinsicSize();
329     if (!intrinsicSize.width() || !intrinsicSize.height())
330         return contentRect;
331
332     LayoutRect finalRect = contentRect;
333     switch (objectFit) {
334     case ObjectFitContain:
335     case ObjectFitScaleDown:
336     case ObjectFitCover:
337         finalRect.setSize(finalRect.size().fitToAspectRatio(intrinsicSize, objectFit == ObjectFitCover ? AspectRatioFitGrow : AspectRatioFitShrink));
338         if (objectFit != ObjectFitScaleDown || finalRect.width() <= intrinsicSize.width())
339             break;
340         // fall through
341     case ObjectFitNone:
342         finalRect.setSize(intrinsicSize);
343         break;
344     case ObjectFitFill:
345         break;
346     default:
347         ASSERT_NOT_REACHED();
348     }
349
350     LayoutUnit xOffset = minimumValueForLength(style()->objectPosition().x(), contentRect.width() - finalRect.width());
351     LayoutUnit yOffset = minimumValueForLength(style()->objectPosition().y(), contentRect.height() - finalRect.height());
352     finalRect.move(xOffset, yOffset);
353
354     return finalRect;
355 }
356
357 void RenderReplaced::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
358 {
359     // If there's an embeddedContentBox() of a remote, referenced document available, this code-path should never be used.
360     ASSERT(!embeddedContentBox());
361     intrinsicSize = FloatSize(intrinsicLogicalWidth().toFloat(), intrinsicLogicalHeight().toFloat());
362
363     // Figure out if we need to compute an intrinsic ratio.
364     if (intrinsicSize.isEmpty() || !rendererHasAspectRatio(this))
365         return;
366
367     intrinsicRatio = intrinsicSize.width() / intrinsicSize.height();
368 }
369
370 LayoutUnit RenderReplaced::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
371 {
372     if (style()->logicalWidth().isSpecified() || style()->logicalWidth().isIntrinsic())
373         return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
374
375     RenderBox* contentRenderer = embeddedContentBox();
376
377     // 10.3.2 Inline, replaced elements: http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width
378     double intrinsicRatio = 0;
379     FloatSize constrainedSize;
380     computeAspectRatioInformationForRenderBox(contentRenderer, constrainedSize, intrinsicRatio);
381
382     if (style()->logicalWidth().isAuto()) {
383         bool computedHeightIsAuto = hasAutoHeightOrContainingBlockWithAutoHeight();
384         bool hasIntrinsicWidth = constrainedSize.width() > 0;
385
386         // 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'.
387         if (computedHeightIsAuto && hasIntrinsicWidth)
388             return computeReplacedLogicalWidthRespectingMinMaxWidth(constrainedSize.width(), shouldComputePreferred);
389
390         bool hasIntrinsicHeight = constrainedSize.height() > 0;
391         if (intrinsicRatio) {
392             // 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;
393             // 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
394             // of 'width' is: (used height) * (intrinsic ratio)
395             if (intrinsicRatio && ((computedHeightIsAuto && !hasIntrinsicWidth && hasIntrinsicHeight) || !computedHeightIsAuto)) {
396                 LayoutUnit logicalHeight = computeReplacedLogicalHeight();
397                 return computeReplacedLogicalWidthRespectingMinMaxWidth(roundToInt(round(logicalHeight * intrinsicRatio)), shouldComputePreferred);
398             }
399
400             // 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
401             // '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
402             // the used value of 'width' is calculated from the constraint equation used for block-level, non-replaced elements in normal flow.
403             if (computedHeightIsAuto && !hasIntrinsicWidth && !hasIntrinsicHeight) {
404                 // The aforementioned 'constraint equation' used for block-level, non-replaced elements in normal flow:
405                 // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
406                 LayoutUnit logicalWidth;
407                 // FIXME: This walking up the containgBlock chain to find the first one with a specified width is bonkers.
408                 // If nothing else, it requires making sure that computeReplacedLogicalWidthRespectingMinMaxWidth cannot
409                 // depend on the width of the replaced element or we infinite loop. Right now we do that in
410                 // firstContainingBlockWithLogicalWidth by checking that width/min-width/max-width are all specified.
411                 //
412                 // Firefox 27 seems to only do this if the <svg> has a viewbox.
413                 if (RenderBlock* blockWithWidth = firstContainingBlockWithLogicalWidth(this)) {
414                     logicalWidth = blockWithWidth->computeReplacedLogicalWidthRespectingMinMaxWidth(blockWithWidth->computeReplacedLogicalWidthUsing(blockWithWidth->style()->logicalWidth()), shouldComputePreferred);
415                 } else {
416                     // FIXME: If shouldComputePreferred == ComputePreferred, then we're reading this during preferred width
417                     // computation, at which point this is reading stale data from a previous layout.
418                     logicalWidth = containingBlock()->availableLogicalWidth();
419                 }
420
421                 // This solves above equation for 'width' (== logicalWidth).
422                 LayoutUnit marginStart = minimumValueForLength(style()->marginStart(), logicalWidth);
423                 LayoutUnit marginEnd = minimumValueForLength(style()->marginEnd(), logicalWidth);
424                 logicalWidth = max<LayoutUnit>(0, logicalWidth - (marginStart + marginEnd + (width() - clientWidth())));
425                 return computeReplacedLogicalWidthRespectingMinMaxWidth(logicalWidth, shouldComputePreferred);
426             }
427         }
428
429         // 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'.
430         if (hasIntrinsicWidth)
431             return computeReplacedLogicalWidthRespectingMinMaxWidth(constrainedSize.width(), shouldComputePreferred);
432
433         // 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
434         // 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.
435         // Note: We fall through and instead return intrinsicLogicalWidth() here - to preserve existing WebKit behavior, which might or might not be correct, or desired.
436         // 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)
437         // has no intrinsic size, which is wrong per CSS 2.1, but matches our behavior since a long time.
438     }
439
440     return computeReplacedLogicalWidthRespectingMinMaxWidth(intrinsicLogicalWidth(), shouldComputePreferred);
441 }
442
443 LayoutUnit RenderReplaced::computeReplacedLogicalHeight() const
444 {
445     // 10.5 Content height: the 'height' property: http://www.w3.org/TR/CSS21/visudet.html#propdef-height
446     if (hasReplacedLogicalHeight())
447         return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
448
449     RenderBox* contentRenderer = embeddedContentBox();
450
451     // 10.6.2 Inline, replaced elements: http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-height
452     double intrinsicRatio = 0;
453     FloatSize constrainedSize;
454     computeAspectRatioInformationForRenderBox(contentRenderer, constrainedSize, intrinsicRatio);
455
456     bool widthIsAuto = style()->logicalWidth().isAuto();
457     bool hasIntrinsicHeight = constrainedSize.height() > 0;
458
459     // 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'.
460     if (widthIsAuto && hasIntrinsicHeight)
461         return computeReplacedLogicalHeightRespectingMinMaxHeight(constrainedSize.height());
462
463     // Otherwise, if 'height' has a computed value of 'auto', and the element has an intrinsic ratio then the used value of 'height' is:
464     // (used width) / (intrinsic ratio)
465     if (intrinsicRatio)
466         return computeReplacedLogicalHeightRespectingMinMaxHeight(roundToInt(round(availableLogicalWidth() / intrinsicRatio)));
467
468     // 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'.
469     if (hasIntrinsicHeight)
470         return computeReplacedLogicalHeightRespectingMinMaxHeight(constrainedSize.height());
471
472     // 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
473     // 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.
474     return computeReplacedLogicalHeightRespectingMinMaxHeight(intrinsicLogicalHeight());
475 }
476
477 void RenderReplaced::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
478 {
479     minLogicalWidth = maxLogicalWidth = intrinsicLogicalWidth();
480 }
481
482 void RenderReplaced::computePreferredLogicalWidths()
483 {
484     ASSERT(preferredLogicalWidthsDirty());
485
486     // We cannot resolve any percent logical width here as the available logical
487     // width may not be set on our containing block.
488     if (style()->logicalWidth().isPercent())
489         computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
490     else
491         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = computeReplacedLogicalWidth(ComputePreferred);
492
493     RenderStyle* styleToUse = style();
494     if (styleToUse->logicalWidth().isPercent() || styleToUse->logicalMaxWidth().isPercent())
495         m_minPreferredLogicalWidth = 0;
496
497     if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
498         m_maxPreferredLogicalWidth = max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
499         m_minPreferredLogicalWidth = max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
500     }
501
502     if (styleToUse->logicalMaxWidth().isFixed()) {
503         m_maxPreferredLogicalWidth = min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
504         m_minPreferredLogicalWidth = min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
505     }
506
507     LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
508     m_minPreferredLogicalWidth += borderAndPadding;
509     m_maxPreferredLogicalWidth += borderAndPadding;
510
511     clearPreferredLogicalWidthsDirty();
512 }
513
514 PositionWithAffinity RenderReplaced::positionForPoint(const LayoutPoint& point)
515 {
516     // FIXME: This code is buggy if the replaced element is relative positioned.
517     InlineBox* box = inlineBoxWrapper();
518     RootInlineBox* rootBox = box ? &box->root() : 0;
519
520     LayoutUnit top = rootBox ? rootBox->selectionTop() : logicalTop();
521     LayoutUnit bottom = rootBox ? rootBox->selectionBottom() : logicalBottom();
522
523     LayoutUnit blockDirectionPosition = isHorizontalWritingMode() ? point.y() + y() : point.x() + x();
524     LayoutUnit lineDirectionPosition = isHorizontalWritingMode() ? point.x() + x() : point.y() + y();
525
526     if (blockDirectionPosition < top)
527         return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM); // coordinates are above
528
529     if (blockDirectionPosition >= bottom)
530         return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM); // coordinates are below
531
532     if (node()) {
533         if (lineDirectionPosition <= logicalLeft() + (logicalWidth() / 2))
534             return createPositionWithAffinity(0, DOWNSTREAM);
535         return createPositionWithAffinity(1, DOWNSTREAM);
536     }
537
538     return RenderBox::positionForPoint(point);
539 }
540
541 LayoutRect RenderReplaced::selectionRectForRepaint(const RenderLayerModelObject* repaintContainer, bool clipToVisibleContent)
542 {
543     ASSERT(!needsLayout());
544
545     if (!isSelected())
546         return LayoutRect();
547
548     LayoutRect rect = localSelectionRect();
549     if (clipToVisibleContent)
550         computeRectForRepaint(repaintContainer, rect);
551     else
552         rect = localToContainerQuad(FloatRect(rect), repaintContainer).enclosingBoundingBox();
553
554     return rect;
555 }
556
557 LayoutRect RenderReplaced::localSelectionRect(bool checkWhetherSelected) const
558 {
559     if (checkWhetherSelected && !isSelected())
560         return LayoutRect();
561
562     if (!inlineBoxWrapper())
563         // We're a block-level replaced element.  Just return our own dimensions.
564         return LayoutRect(LayoutPoint(), size());
565
566     RootInlineBox& root = inlineBoxWrapper()->root();
567     LayoutUnit newLogicalTop = root.block().style()->isFlippedBlocksWritingMode() ? inlineBoxWrapper()->logicalBottom() - root.selectionBottom() : root.selectionTop() - inlineBoxWrapper()->logicalTop();
568     if (root.block().style()->isHorizontalWritingMode())
569         return LayoutRect(0, newLogicalTop, width(), root.selectionHeight());
570     return LayoutRect(newLogicalTop, 0, root.selectionHeight(), height());
571 }
572
573 void RenderReplaced::setSelectionState(SelectionState state)
574 {
575     // The selection state for our containing block hierarchy is updated by the base class call.
576     RenderBox::setSelectionState(state);
577
578     if (inlineBoxWrapper() && canUpdateSelectionOnRootLineBoxes())
579         inlineBoxWrapper()->root().setHasSelectedChildren(isSelected());
580 }
581
582 bool RenderReplaced::isSelected() const
583 {
584     SelectionState s = selectionState();
585     if (s == SelectionNone)
586         return false;
587     if (s == SelectionInside)
588         return true;
589
590     int selectionStart, selectionEnd;
591     selectionStartEnd(selectionStart, selectionEnd);
592     if (s == SelectionStart)
593         return selectionStart == 0;
594
595     int end = node()->hasChildren() ? node()->countChildren() : 1;
596     if (s == SelectionEnd)
597         return selectionEnd == end;
598     if (s == SelectionBoth)
599         return selectionStart == 0 && selectionEnd == end;
600
601     ASSERT(0);
602     return false;
603 }
604
605 LayoutRect RenderReplaced::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
606 {
607     if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
608         return LayoutRect();
609
610     // The selectionRect can project outside of the overflowRect, so take their union
611     // for repainting to avoid selection painting glitches.
612     LayoutRect r = unionRect(localSelectionRect(false), visualOverflowRect());
613
614     RenderView* v = view();
615     if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && v) {
616         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
617         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
618         r.move(v->layoutDelta());
619     }
620
621     computeRectForRepaint(repaintContainer, r);
622     return r;
623 }
624
625 }