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