Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderBox.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
7  * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  *
24  */
25
26 #include "config.h"
27 #include "core/rendering/RenderBox.h"
28
29 #include "core/HTMLNames.h"
30 #include "core/dom/Document.h"
31 #include "core/editing/htmlediting.h"
32 #include "core/frame/FrameHost.h"
33 #include "core/frame/FrameView.h"
34 #include "core/frame/LocalFrame.h"
35 #include "core/frame/PinchViewport.h"
36 #include "core/frame/Settings.h"
37 #include "core/html/HTMLElement.h"
38 #include "core/html/HTMLFrameElementBase.h"
39 #include "core/html/HTMLFrameOwnerElement.h"
40 #include "core/page/AutoscrollController.h"
41 #include "core/page/EventHandler.h"
42 #include "core/page/Page.h"
43 #include "core/paint/BackgroundImageGeometry.h"
44 #include "core/paint/BoxPainter.h"
45 #include "core/rendering/HitTestResult.h"
46 #include "core/rendering/PaintInfo.h"
47 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
48 #include "core/rendering/RenderFlexibleBox.h"
49 #include "core/rendering/RenderGeometryMap.h"
50 #include "core/rendering/RenderGrid.h"
51 #include "core/rendering/RenderInline.h"
52 #include "core/rendering/RenderLayer.h"
53 #include "core/rendering/RenderListBox.h"
54 #include "core/rendering/RenderListMarker.h"
55 #include "core/rendering/RenderTableCell.h"
56 #include "core/rendering/RenderView.h"
57 #include "core/rendering/compositing/RenderLayerCompositor.h"
58 #include "platform/LengthFunctions.h"
59 #include "platform/geometry/FloatQuad.h"
60 #include "platform/geometry/TransformState.h"
61 #include <algorithm>
62 #include <math.h>
63
64 namespace blink {
65
66 using namespace HTMLNames;
67
68 // Used by flexible boxes when flexing this element and by table cells.
69 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
70
71 // Used by grid elements to properly size their grid items.
72 // FIXME: Move these into RenderBoxRareData.
73 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0;
74 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0;
75
76
77 // Size of border belt for autoscroll. When mouse pointer in border belt,
78 // autoscroll is started.
79 static const int autoscrollBeltSize = 20;
80 static const unsigned backgroundObscurationTestMaxDepth = 4;
81
82 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
83 {
84     ASSERT(bodyElementRenderer->isBody());
85     // The <body> only paints its background if the root element has defined a background independent of the body,
86     // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
87     RenderObject* documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
88     return documentElementRenderer
89         && !documentElementRenderer->hasBackground()
90         && (documentElementRenderer == bodyElementRenderer->parent());
91 }
92
93 RenderBox::RenderBox(ContainerNode* node)
94     : RenderBoxModelObject(node)
95     , m_intrinsicContentLogicalHeight(-1)
96     , m_minPreferredLogicalWidth(-1)
97     , m_maxPreferredLogicalWidth(-1)
98 {
99     setIsBox();
100 }
101
102 void RenderBox::willBeDestroyed()
103 {
104     clearOverrideSize();
105     clearContainingBlockOverrideSize();
106
107     RenderBlock::removePercentHeightDescendantIfNeeded(this);
108
109     ShapeOutsideInfo::removeInfo(*this);
110
111     RenderBoxModelObject::willBeDestroyed();
112 }
113
114 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
115 {
116     ASSERT(isFloatingOrOutOfFlowPositioned());
117
118     if (documentBeingDestroyed())
119         return;
120
121     if (isFloating()) {
122         RenderBlockFlow* parentBlockFlow = 0;
123         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
124             if (curr->isRenderBlockFlow()) {
125                 RenderBlockFlow* currBlockFlow = toRenderBlockFlow(curr);
126                 if (!parentBlockFlow || currBlockFlow->containsFloat(this))
127                     parentBlockFlow = currBlockFlow;
128             }
129         }
130
131         if (parentBlockFlow) {
132             parentBlockFlow->markSiblingsWithFloatsForLayout(this);
133             parentBlockFlow->markAllDescendantsWithFloatsForLayout(this, false);
134         }
135     }
136
137     if (isOutOfFlowPositioned())
138         RenderBlock::removePositionedObject(this);
139 }
140
141 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
142 {
143     RenderStyle* oldStyle = style();
144     if (oldStyle) {
145         // The background of the root element or the body element could propagate up to
146         // the canvas. Just dirty the entire canvas when our style changes substantially.
147         if ((diff.needsPaintInvalidation() || diff.needsLayout()) && node()
148             && (isHTMLHtmlElement(*node()) || isHTMLBodyElement(*node()))) {
149             view()->setShouldDoFullPaintInvalidation(true);
150
151             if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
152                 view()->compositor()->setNeedsUpdateFixedBackground();
153         }
154
155         // When a layout hint happens and an object's position style changes, we have to do a layout
156         // to dirty the render tree using the old position value now.
157         if (diff.needsFullLayout() && parent() && oldStyle->position() != newStyle.position()) {
158             markContainingBlocksForLayout();
159             if (oldStyle->position() == StaticPosition)
160                 setShouldDoFullPaintInvalidation(true);
161             else if (newStyle.hasOutOfFlowPosition())
162                 parent()->setChildNeedsLayout();
163             if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
164                 removeFloatingOrPositionedChildFromBlockLists();
165         }
166     // FIXME: This branch runs when !oldStyle, which means that layout was never called
167     // so what's the point in invalidating the whole view that we never painted?
168     } else if (isBody()) {
169         view()->setShouldDoFullPaintInvalidation(true);
170     }
171
172     RenderBoxModelObject::styleWillChange(diff, newStyle);
173 }
174
175 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
176 {
177     // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
178     // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
179     // writing mode value before style change here.
180     bool oldHorizontalWritingMode = isHorizontalWritingMode();
181
182     RenderBoxModelObject::styleDidChange(diff, oldStyle);
183
184     RenderStyle* newStyle = style();
185     if (needsLayout() && oldStyle)
186         RenderBlock::removePercentHeightDescendantIfNeeded(this);
187
188     if (RenderBlock::hasPercentHeightContainerMap() && slowFirstChild()
189         && oldHorizontalWritingMode != isHorizontalWritingMode())
190         RenderBlock::clearPercentHeightDescendantsFrom(this);
191
192     // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
193     // new zoomed coordinate space.
194     if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) {
195         if (int left = layer()->scrollableArea()->scrollXOffset()) {
196             left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
197             layer()->scrollableArea()->scrollToXOffset(left);
198         }
199         if (int top = layer()->scrollableArea()->scrollYOffset()) {
200             top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
201             layer()->scrollableArea()->scrollToYOffset(top);
202         }
203     }
204
205     // Our opaqueness might have changed without triggering layout.
206     if (diff.needsPaintInvalidation()) {
207         RenderObject* parentToInvalidate = parent();
208         for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
209             parentToInvalidate->invalidateBackgroundObscurationStatus();
210             parentToInvalidate = parentToInvalidate->parent();
211         }
212     }
213
214     if (isDocumentElement() || isBody())
215         document().view()->recalculateScrollbarOverlayStyle();
216
217     updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle);
218     updateGridPositionAfterStyleChange(oldStyle);
219 }
220
221 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
222 {
223     const ShapeValue* shapeOutside = style.shapeOutside();
224     const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : RenderStyle::initialShapeOutside();
225
226     Length shapeMargin = style.shapeMargin();
227     Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
228
229     float shapeImageThreshold = style.shapeImageThreshold();
230     float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
231
232     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
233     if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
234         return;
235
236     if (!shapeOutside)
237         ShapeOutsideInfo::removeInfo(*this);
238     else
239         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
240
241     if (shapeOutside || shapeOutside != oldShapeOutside)
242         markShapeOutsideDependentsForLayout();
243 }
244
245 void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle* oldStyle)
246 {
247     if (!oldStyle || !parent() || !parent()->isRenderGrid())
248         return;
249
250     if (oldStyle->gridColumnStart() == style()->gridColumnStart()
251         && oldStyle->gridColumnEnd() == style()->gridColumnEnd()
252         && oldStyle->gridRowStart() == style()->gridRowStart()
253         && oldStyle->gridRowEnd() == style()->gridRowEnd()
254         && oldStyle->order() == style()->order()
255         && oldStyle->hasOutOfFlowPosition() == style()->hasOutOfFlowPosition())
256         return;
257
258     // It should be possible to not dirty the grid in some cases (like moving an explicitly placed grid item).
259     // For now, it's more simple to just always recompute the grid.
260     toRenderGrid(parent())->dirtyGrid();
261 }
262
263 void RenderBox::updateFromStyle()
264 {
265     RenderBoxModelObject::updateFromStyle();
266
267     RenderStyle* styleToUse = style();
268     bool isRootObject = isDocumentElement();
269     bool isViewObject = isRenderView();
270
271     // The root and the RenderView always paint their backgrounds/borders.
272     if (isRootObject || isViewObject)
273         setHasBoxDecorationBackground(true);
274
275     setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
276
277     bool boxHasOverflowClip = false;
278     if (!styleToUse->isOverflowVisible() && isRenderBlock() && !isViewObject) {
279         // If overflow has been propagated to the viewport, it has no effect here.
280         if (node() != document().viewportDefiningElement())
281             boxHasOverflowClip = true;
282     }
283
284     if (boxHasOverflowClip != hasOverflowClip()) {
285         // FIXME: This shouldn't be required if we tracked the visual overflow
286         // generated by positioned children or self painting layers. crbug.com/345403
287         for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling())
288             child->setShouldDoFullPaintInvalidationIfSelfPaintingLayer(true);
289     }
290
291     setHasOverflowClip(boxHasOverflowClip);
292
293     setHasTransform(styleToUse->hasTransformRelatedProperty());
294     setHasReflection(styleToUse->boxReflect());
295 }
296
297 void RenderBox::layout()
298 {
299     ASSERT(needsLayout());
300
301     RenderObject* child = slowFirstChild();
302     if (!child) {
303         clearNeedsLayout();
304         return;
305     }
306
307     LayoutState state(*this, locationOffset());
308     while (child) {
309         child->layoutIfNeeded();
310         ASSERT(!child->needsLayout());
311         child = child->nextSibling();
312     }
313     invalidateBackgroundObscurationStatus();
314     clearNeedsLayout();
315 }
316
317 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
318 // excluding border and scrollbar.
319 LayoutUnit RenderBox::clientWidth() const
320 {
321     return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
322 }
323
324 LayoutUnit RenderBox::clientHeight() const
325 {
326     return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
327 }
328
329 int RenderBox::pixelSnappedClientWidth() const
330 {
331     return snapSizeToPixel(clientWidth(), x() + clientLeft());
332 }
333
334 int RenderBox::pixelSnappedClientHeight() const
335 {
336     return snapSizeToPixel(clientHeight(), y() + clientTop());
337 }
338
339 int RenderBox::pixelSnappedOffsetWidth() const
340 {
341     return snapSizeToPixel(offsetWidth(), x() + clientLeft());
342 }
343
344 int RenderBox::pixelSnappedOffsetHeight() const
345 {
346     return snapSizeToPixel(offsetHeight(), y() + clientTop());
347 }
348
349 LayoutUnit RenderBox::scrollWidth() const
350 {
351     if (hasOverflowClip())
352         return layer()->scrollableArea()->scrollWidth();
353     // For objects with visible overflow, this matches IE.
354     // FIXME: Need to work right with writing modes.
355     if (style()->isLeftToRightDirection())
356         return std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft());
357     return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
358 }
359
360 LayoutUnit RenderBox::scrollHeight() const
361 {
362     if (hasOverflowClip())
363         return layer()->scrollableArea()->scrollHeight();
364     // For objects with visible overflow, this matches IE.
365     // FIXME: Need to work right with writing modes.
366     return std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop());
367 }
368
369 LayoutUnit RenderBox::scrollLeft() const
370 {
371     return hasOverflowClip() ? layer()->scrollableArea()->scrollXOffset() : 0;
372 }
373
374 LayoutUnit RenderBox::scrollTop() const
375 {
376     return hasOverflowClip() ? layer()->scrollableArea()->scrollYOffset() : 0;
377 }
378
379 int RenderBox::pixelSnappedScrollWidth() const
380 {
381     return snapSizeToPixel(scrollWidth(), x() + clientLeft());
382 }
383
384 int RenderBox::pixelSnappedScrollHeight() const
385 {
386     if (hasOverflowClip())
387         return layer()->scrollableArea()->scrollHeight();
388     // For objects with visible overflow, this matches IE.
389     // FIXME: Need to work right with writing modes.
390     return snapSizeToPixel(scrollHeight(), y() + clientTop());
391 }
392
393 void RenderBox::setScrollLeft(LayoutUnit newLeft)
394 {
395     // This doesn't hit in any tests, but since the equivalent code in setScrollTop
396     // does, presumably this code does as well.
397     DisableCompositingQueryAsserts disabler;
398
399     if (hasOverflowClip())
400         layer()->scrollableArea()->scrollToXOffset(newLeft, ScrollOffsetClamped);
401 }
402
403 void RenderBox::setScrollTop(LayoutUnit newTop)
404 {
405     // Hits in compositing/overflow/do-not-assert-on-invisible-composited-layers.html
406     DisableCompositingQueryAsserts disabler;
407
408     if (hasOverflowClip())
409         layer()->scrollableArea()->scrollToYOffset(newTop, ScrollOffsetClamped);
410 }
411
412 void RenderBox::scrollToOffset(const IntSize& offset)
413 {
414     ASSERT(hasOverflowClip());
415
416     // This doesn't hit in any tests, but since the equivalent code in setScrollTop
417     // does, presumably this code does as well.
418     DisableCompositingQueryAsserts disabler;
419     layer()->scrollableArea()->scrollToOffset(offset, ScrollOffsetClamped);
420 }
421
422 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
423 {
424     // If scrollbars aren't explicitly forbidden, permit scrolling.
425     if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
426         return true;
427
428     // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
429     if (frameView->wasScrolledByUser())
430         return false;
431
432     // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
433     // like navigation to an anchor.
434     Page* page = frameView->frame().page();
435     if (!page)
436         return false;
437     return !page->autoscrollController().autoscrollInProgress();
438 }
439
440 void RenderBox::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
441 {
442     // Presumably the same issue as in setScrollTop. See crbug.com/343132.
443     DisableCompositingQueryAsserts disabler;
444
445     RenderBox* parentBox = 0;
446     LayoutRect newRect = rect;
447
448     bool restrictedByLineClamp = false;
449     if (parent()) {
450         parentBox = parent()->enclosingBox();
451         restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
452     }
453
454     if (hasOverflowClip() && !restrictedByLineClamp) {
455         // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
456         // This will prevent us from revealing text hidden by the slider in Safari RSS.
457         newRect = layer()->scrollableArea()->exposeRect(rect, alignX, alignY);
458     } else if (!parentBox && canBeProgramaticallyScrolled()) {
459         if (FrameView* frameView = this->frameView()) {
460             HTMLFrameOwnerElement* ownerElement = document().ownerElement();
461
462             if (ownerElement && ownerElement->renderer()) {
463                 HTMLFrameElementBase* frameElementBase = isHTMLFrameElementBase(*ownerElement) ? toHTMLFrameElementBase(ownerElement) : 0;
464                 if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
465                     LayoutRect viewRect = frameView->visibleContentRect();
466                     LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
467
468                     int xOffset = roundToInt(exposeRect.x());
469                     int yOffset = roundToInt(exposeRect.y());
470                     // Adjust offsets if they're outside of the allowable range.
471                     xOffset = std::max(0, std::min(frameView->contentsWidth(), xOffset));
472                     yOffset = std::max(0, std::min(frameView->contentsHeight(), yOffset));
473
474                     frameView->setScrollPosition(IntPoint(xOffset, yOffset));
475                     if (frameView->safeToPropagateScrollToParent()) {
476                         parentBox = ownerElement->renderer()->enclosingBox();
477                         // FIXME: This doesn't correctly convert the rect to
478                         // absolute coordinates in the parent.
479                         newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
480                         newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
481                     } else {
482                         parentBox = 0;
483                     }
484                 }
485             } else {
486                 if (frame()->settings()->pinchVirtualViewportEnabled()) {
487                     PinchViewport& pinchViewport = frame()->page()->frameHost().pinchViewport();
488                     LayoutRect r = ScrollAlignment::getRectToExpose(LayoutRect(pinchViewport.visibleRectInDocument()), rect, alignX, alignY);
489                     pinchViewport.scrollIntoView(r);
490                 } else {
491                     LayoutRect viewRect = frameView->visibleContentRect();
492                     LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
493                     frameView->setScrollPosition(roundedIntPoint(r.location()));
494                 }
495             }
496         }
497     }
498
499     if (frame()->page()->autoscrollController().autoscrollInProgress())
500         parentBox = enclosingScrollableBox();
501
502     if (parentBox)
503         parentBox->scrollRectToVisible(newRect, alignX, alignY);
504 }
505
506 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
507 {
508     rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
509 }
510
511 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
512 {
513     quads.append(localToAbsoluteQuad(FloatRect(0, 0, width().toFloat(), height().toFloat()), 0 /* mode */, wasFixed));
514 }
515
516 void RenderBox::updateLayerTransformAfterLayout()
517 {
518     // Transform-origin depends on box size, so we need to update the layer transform after layout.
519     if (hasLayer())
520         layer()->updateTransformationMatrix();
521 }
522
523 LayoutUnit RenderBox::constrainLogicalWidthByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb) const
524 {
525     RenderStyle* styleToUse = style();
526     if (!styleToUse->logicalMaxWidth().isMaxSizeNone())
527         logicalWidth = std::min(logicalWidth, computeLogicalWidthUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb));
528     return std::max(logicalWidth, computeLogicalWidthUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb));
529 }
530
531 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
532 {
533     RenderStyle* styleToUse = style();
534     if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
535         LayoutUnit maxH = computeLogicalHeightUsing(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
536         if (maxH != -1)
537             logicalHeight = std::min(logicalHeight, maxH);
538     }
539     return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse->logicalMinHeight(), intrinsicContentHeight));
540 }
541
542 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
543 {
544     RenderStyle* styleToUse = style();
545     if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
546         LayoutUnit maxH = computeContentLogicalHeight(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
547         if (maxH != -1)
548             logicalHeight = std::min(logicalHeight, maxH);
549     }
550     return std::max(logicalHeight, computeContentLogicalHeight(styleToUse->logicalMinHeight(), intrinsicContentHeight));
551 }
552
553 IntRect RenderBox::absoluteContentBox() const
554 {
555     // This is wrong with transforms and flipped writing modes.
556     IntRect rect = pixelSnappedIntRect(contentBoxRect());
557     FloatPoint absPos = localToAbsolute();
558     rect.move(absPos.x(), absPos.y());
559     return rect;
560 }
561
562 FloatQuad RenderBox::absoluteContentQuad() const
563 {
564     LayoutRect rect = contentBoxRect();
565     return localToAbsoluteQuad(FloatRect(rect));
566 }
567
568 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*) const
569 {
570     if (!size().isEmpty())
571         rects.append(LayoutRect(additionalOffset, size()));
572 }
573
574 bool RenderBox::canResize() const
575 {
576     // We need a special case for <iframe> because they never have
577     // hasOverflowClip(). However, they do "implicitly" clip their contents, so
578     // we want to allow resizing them also.
579     return (hasOverflowClip() || isRenderIFrame()) && style()->resize() != RESIZE_NONE;
580 }
581
582 void RenderBox::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
583 {
584     LayoutPoint adjustedLayerOffset = layerOffset + locationOffset();
585     RenderBoxModelObject::addLayerHitTestRects(layerRects, currentLayer, adjustedLayerOffset, containerRect);
586 }
587
588 void RenderBox::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const
589 {
590     if (!size().isEmpty())
591         rects.append(LayoutRect(layerOffset, size()));
592 }
593
594 int RenderBox::reflectionOffset() const
595 {
596     if (!style()->boxReflect())
597         return 0;
598     if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
599         return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width());
600     return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height());
601 }
602
603 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
604 {
605     if (!style()->boxReflect())
606         return LayoutRect();
607
608     LayoutRect box = borderBoxRect();
609     LayoutRect result = r;
610     switch (style()->boxReflect()->direction()) {
611         case ReflectionBelow:
612             result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
613             break;
614         case ReflectionAbove:
615             result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
616             break;
617         case ReflectionLeft:
618             result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
619             break;
620         case ReflectionRight:
621             result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
622             break;
623     }
624     return result;
625 }
626
627 int RenderBox::verticalScrollbarWidth() const
628 {
629     if (!hasOverflowClip() || style()->overflowY() == OOVERLAY)
630         return 0;
631
632     return layer()->scrollableArea()->verticalScrollbarWidth();
633 }
634
635 int RenderBox::horizontalScrollbarHeight() const
636 {
637     if (!hasOverflowClip() || style()->overflowX() == OOVERLAY)
638         return 0;
639
640     return layer()->scrollableArea()->horizontalScrollbarHeight();
641 }
642
643 int RenderBox::instrinsicScrollbarLogicalWidth() const
644 {
645     if (!hasOverflowClip())
646         return 0;
647
648     if (isHorizontalWritingMode() && style()->overflowY() == OSCROLL) {
649         ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasVerticalScrollbar());
650         return verticalScrollbarWidth();
651     }
652
653     if (!isHorizontalWritingMode() && style()->overflowX() == OSCROLL) {
654         ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasHorizontalScrollbar());
655         return horizontalScrollbarHeight();
656     }
657
658     return 0;
659 }
660
661 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float delta)
662 {
663     // Presumably the same issue as in setScrollTop. See crbug.com/343132.
664     DisableCompositingQueryAsserts disabler;
665
666     // Logical scroll is a higher level concept, all directions by here must be physical
667     ASSERT(!isLogical(direction));
668
669     if (!layer() || !layer()->scrollableArea())
670         return false;
671
672     return layer()->scrollableArea()->scroll(direction, granularity, delta);
673 }
674
675 bool RenderBox::canBeScrolledAndHasScrollableArea() const
676 {
677     return canBeProgramaticallyScrolled() && (pixelSnappedScrollHeight() != pixelSnappedClientHeight() || pixelSnappedScrollWidth() != pixelSnappedClientWidth());
678 }
679
680 bool RenderBox::canBeProgramaticallyScrolled() const
681 {
682     Node* node = this->node();
683     if (node && node->isDocumentNode())
684         return true;
685
686     if (!hasOverflowClip())
687         return false;
688
689     bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
690     if (scrollsOverflow() && hasScrollableOverflow)
691         return true;
692
693     return node && node->hasEditableStyle();
694 }
695
696 bool RenderBox::usesCompositedScrolling() const
697 {
698     return hasOverflowClip() && hasLayer() && layer()->scrollableArea()->usesCompositedScrolling();
699 }
700
701 void RenderBox::autoscroll(const IntPoint& position)
702 {
703     LocalFrame* frame = this->frame();
704     if (!frame)
705         return;
706
707     FrameView* frameView = frame->view();
708     if (!frameView)
709         return;
710
711     IntPoint currentDocumentPosition = frameView->windowToContents(position);
712     scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
713 }
714
715 bool RenderBox::autoscrollInProgress() const
716 {
717     return frame() && frame()->page() && frame()->page()->autoscrollController().autoscrollInProgress(this);
718 }
719
720 // There are two kinds of renderer that can autoscroll.
721 bool RenderBox::canAutoscroll() const
722 {
723     if (node() && node()->isDocumentNode())
724         return view()->frameView()->isScrollable();
725
726     // Check for a box that can be scrolled in its own right.
727     return canBeScrolledAndHasScrollableArea();
728 }
729
730 // If specified point is in border belt, returned offset denotes direction of
731 // scrolling.
732 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
733 {
734     if (!frame())
735         return IntSize();
736
737     FrameView* frameView = frame()->view();
738     if (!frameView)
739         return IntSize();
740
741     IntRect box(absoluteBoundingBoxRect());
742     box.move(view()->frameView()->scrollOffset());
743     IntRect windowBox = view()->frameView()->contentsToWindow(box);
744
745     IntPoint windowAutoscrollPoint = windowPoint;
746
747     if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
748         windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
749     else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
750         windowAutoscrollPoint.move(autoscrollBeltSize, 0);
751
752     if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
753         windowAutoscrollPoint.move(0, -autoscrollBeltSize);
754     else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
755         windowAutoscrollPoint.move(0, autoscrollBeltSize);
756
757     return windowAutoscrollPoint - windowPoint;
758 }
759
760 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
761 {
762     while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
763         if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document().ownerElement())
764             renderer = renderer->document().ownerElement()->renderer();
765         else
766             renderer = renderer->parent();
767     }
768
769     return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
770 }
771
772 static inline int adjustedScrollDelta(int beginningDelta)
773 {
774     // This implemention matches Firefox's.
775     // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
776     const int speedReducer = 12;
777
778     int adjustedDelta = beginningDelta / speedReducer;
779     if (adjustedDelta > 1)
780         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
781     else if (adjustedDelta < -1)
782         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
783
784     return adjustedDelta;
785 }
786
787 static inline IntSize adjustedScrollDelta(const IntSize& delta)
788 {
789     return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
790 }
791
792 void RenderBox::panScroll(const IntPoint& sourcePoint)
793 {
794     LocalFrame* frame = this->frame();
795     if (!frame)
796         return;
797
798     IntPoint lastKnownMousePosition = frame->eventHandler().lastKnownMousePosition();
799
800     // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
801     static IntPoint previousMousePosition;
802     if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
803         lastKnownMousePosition = previousMousePosition;
804     else
805         previousMousePosition = lastKnownMousePosition;
806
807     IntSize delta = lastKnownMousePosition - sourcePoint;
808
809     if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
810         delta.setWidth(0);
811     if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
812         delta.setHeight(0);
813
814     scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
815 }
816
817 void RenderBox::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp)
818 {
819     if (delta.isZero())
820         return;
821
822     bool restrictedByLineClamp = false;
823     if (parent())
824         restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
825
826     if (hasOverflowClip() && !restrictedByLineClamp) {
827         IntSize newScrollOffset = layer()->scrollableArea()->adjustedScrollOffset() + delta;
828         layer()->scrollableArea()->scrollToOffset(newScrollOffset, clamp);
829
830         // If this layer can't do the scroll we ask the next layer up that can scroll to try
831         IntSize remainingScrollOffset = newScrollOffset - layer()->scrollableArea()->adjustedScrollOffset();
832         if (!remainingScrollOffset.isZero() && parent()) {
833             if (RenderBox* scrollableBox = enclosingScrollableBox())
834                 scrollableBox->scrollByRecursively(remainingScrollOffset, clamp);
835
836             LocalFrame* frame = this->frame();
837             if (frame && frame->page())
838                 frame->page()->autoscrollController().updateAutoscrollRenderer();
839         }
840     } else if (view()->frameView()) {
841         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
842         // have an overflow clip. Which means that it is a document node that can be scrolled.
843         view()->frameView()->scrollBy(delta);
844
845         // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement?
846         // https://bugs.webkit.org/show_bug.cgi?id=28237
847     }
848 }
849
850 bool RenderBox::needsPreferredWidthsRecalculation() const
851 {
852     return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
853 }
854
855 IntSize RenderBox::scrolledContentOffset() const
856 {
857     ASSERT(hasOverflowClip());
858     ASSERT(hasLayer());
859     return layer()->scrollableArea()->scrollOffset();
860 }
861
862 void RenderBox::applyCachedClipAndScrollOffsetForPaintInvalidation(LayoutRect& paintRect) const
863 {
864     ASSERT(hasLayer());
865     ASSERT(hasOverflowClip());
866
867     flipForWritingMode(paintRect);
868     paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
869
870     // Do not clip scroll layer contents because the compositor expects the whole layer
871     // to be always invalidated in-time.
872     if (usesCompositedScrolling()) {
873         flipForWritingMode(paintRect);
874         return;
875     }
876
877     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
878     // layer's size instead. Even if the layer's size is wrong, the layer itself will issue paint invalidations
879     // anyway if its size does change.
880     LayoutRect clipRect(LayoutPoint(), layer()->size());
881     paintRect = intersection(paintRect, clipRect);
882     flipForWritingMode(paintRect);
883 }
884
885 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
886 {
887     minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
888     maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
889 }
890
891 LayoutUnit RenderBox::minPreferredLogicalWidth() const
892 {
893     if (preferredLogicalWidthsDirty()) {
894 #if ENABLE(ASSERT)
895         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
896 #endif
897         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
898     }
899
900     return m_minPreferredLogicalWidth;
901 }
902
903 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
904 {
905     if (preferredLogicalWidthsDirty()) {
906 #if ENABLE(ASSERT)
907         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
908 #endif
909         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
910     }
911
912     return m_maxPreferredLogicalWidth;
913 }
914
915 bool RenderBox::hasOverrideHeight() const
916 {
917     return m_rareData && m_rareData->m_overrideLogicalContentHeight != -1;
918 }
919
920 bool RenderBox::hasOverrideWidth() const
921 {
922     return m_rareData && m_rareData->m_overrideLogicalContentWidth != -1;
923 }
924
925 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
926 {
927     ASSERT(height >= 0);
928     ensureRareData().m_overrideLogicalContentHeight = height;
929 }
930
931 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
932 {
933     ASSERT(width >= 0);
934     ensureRareData().m_overrideLogicalContentWidth = width;
935 }
936
937 void RenderBox::clearOverrideLogicalContentHeight()
938 {
939     if (m_rareData)
940         m_rareData->m_overrideLogicalContentHeight = -1;
941 }
942
943 void RenderBox::clearOverrideLogicalContentWidth()
944 {
945     if (m_rareData)
946         m_rareData->m_overrideLogicalContentWidth = -1;
947 }
948
949 void RenderBox::clearOverrideSize()
950 {
951     clearOverrideLogicalContentHeight();
952     clearOverrideLogicalContentWidth();
953 }
954
955 LayoutUnit RenderBox::overrideLogicalContentWidth() const
956 {
957     ASSERT(hasOverrideWidth());
958     return m_rareData->m_overrideLogicalContentWidth;
959 }
960
961 LayoutUnit RenderBox::overrideLogicalContentHeight() const
962 {
963     ASSERT(hasOverrideHeight());
964     return m_rareData->m_overrideLogicalContentHeight;
965 }
966
967 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
968 {
969     ASSERT(hasOverrideContainingBlockLogicalWidth());
970     return gOverrideContainingBlockLogicalWidthMap->get(this);
971 }
972
973 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
974 {
975     ASSERT(hasOverrideContainingBlockLogicalHeight());
976     return gOverrideContainingBlockLogicalHeightMap->get(this);
977 }
978
979 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
980 {
981     return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
982 }
983
984 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
985 {
986     return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
987 }
988
989 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
990 {
991     if (!gOverrideContainingBlockLogicalWidthMap)
992         gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
993     gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
994 }
995
996 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
997 {
998     if (!gOverrideContainingBlockLogicalHeightMap)
999         gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
1000     gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1001 }
1002
1003 void RenderBox::clearContainingBlockOverrideSize()
1004 {
1005     if (gOverrideContainingBlockLogicalWidthMap)
1006         gOverrideContainingBlockLogicalWidthMap->remove(this);
1007     clearOverrideContainingBlockContentLogicalHeight();
1008 }
1009
1010 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1011 {
1012     if (gOverrideContainingBlockLogicalHeightMap)
1013         gOverrideContainingBlockLogicalHeightMap->remove(this);
1014 }
1015
1016 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1017 {
1018     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1019     if (style()->boxSizing() == CONTENT_BOX)
1020         return width + bordersPlusPadding;
1021     return std::max(width, bordersPlusPadding);
1022 }
1023
1024 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1025 {
1026     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1027     if (style()->boxSizing() == CONTENT_BOX)
1028         return height + bordersPlusPadding;
1029     return std::max(height, bordersPlusPadding);
1030 }
1031
1032 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1033 {
1034     if (style()->boxSizing() == BORDER_BOX)
1035         width -= borderAndPaddingLogicalWidth();
1036     return std::max<LayoutUnit>(0, width);
1037 }
1038
1039 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1040 {
1041     if (style()->boxSizing() == BORDER_BOX)
1042         height -= borderAndPaddingLogicalHeight();
1043     return std::max<LayoutUnit>(0, height);
1044 }
1045
1046 // Hit Testing
1047 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1048 {
1049     LayoutPoint adjustedLocation = accumulatedOffset + location();
1050
1051     // Check kids first.
1052     for (RenderObject* child = slowLastChild(); child; child = child->previousSibling()) {
1053         if ((!child->hasLayer() || !toRenderLayerModelObject(child)->layer()->isSelfPaintingLayer()) && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1054             updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1055             return true;
1056         }
1057     }
1058
1059     // Check our bounds next. For this purpose always assume that we can only be hit in the
1060     // foreground phase (which is true for replaced elements like images).
1061     LayoutRect boundsRect = borderBoxRect();
1062     boundsRect.moveBy(adjustedLocation);
1063     if (visibleToHitTestRequest(request) && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1064         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1065         if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
1066             return true;
1067     }
1068
1069     return false;
1070 }
1071
1072 void RenderBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1073 {
1074     BoxPainter(*this).paint(paintInfo, paintOffset);
1075 }
1076
1077
1078 void RenderBox::paintBoxDecorationBackground(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1079 {
1080     BoxPainter(*this).paintBoxDecorationBackground(paintInfo, paintOffset);
1081 }
1082
1083
1084 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent)
1085 {
1086     ASSERT(hasBackground());
1087     LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
1088
1089     Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
1090     if (backgroundColor.alpha()) {
1091         paintedExtent = backgroundRect;
1092         return true;
1093     }
1094
1095     if (!style()->backgroundLayers().image() || style()->backgroundLayers().next()) {
1096         paintedExtent =  backgroundRect;
1097         return true;
1098     }
1099
1100     BackgroundImageGeometry geometry;
1101     BoxPainter::calculateBackgroundImageGeometry(*this, 0, style()->backgroundLayers(), backgroundRect, geometry);
1102     if (geometry.hasNonLocalGeometry())
1103         return false;
1104     paintedExtent = geometry.destRect();
1105     return true;
1106 }
1107
1108 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1109 {
1110     if (isBody() && skipBodyBackground(this))
1111         return false;
1112
1113     Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
1114     if (backgroundColor.hasAlpha())
1115         return false;
1116
1117     // If the element has appearance, it might be painted by theme.
1118     // We cannot be sure if theme paints the background opaque.
1119     // In this case it is safe to not assume opaqueness.
1120     // FIXME: May be ask theme if it paints opaque.
1121     if (style()->hasAppearance())
1122         return false;
1123     // FIXME: Check the opaqueness of background images.
1124
1125     // FIXME: Use rounded rect if border radius is present.
1126     if (style()->hasBorderRadius())
1127         return false;
1128     // FIXME: The background color clip is defined by the last layer.
1129     if (style()->backgroundLayers().next())
1130         return false;
1131     LayoutRect backgroundRect;
1132     switch (style()->backgroundClip()) {
1133     case BorderFillBox:
1134         backgroundRect = borderBoxRect();
1135         break;
1136     case PaddingFillBox:
1137         backgroundRect = paddingBoxRect();
1138         break;
1139     case ContentFillBox:
1140         backgroundRect = contentBoxRect();
1141         break;
1142     default:
1143         break;
1144     }
1145     return backgroundRect.contains(localRect);
1146 }
1147
1148 static bool isCandidateForOpaquenessTest(RenderBox* childBox)
1149 {
1150     RenderStyle* childStyle = childBox->style();
1151     if (childStyle->position() != StaticPosition && childBox->containingBlock() != childBox->parent())
1152         return false;
1153     if (childStyle->visibility() != VISIBLE || childStyle->shapeOutside())
1154         return false;
1155     if (!childBox->width() || !childBox->height())
1156         return false;
1157     if (RenderLayer* childLayer = childBox->layer()) {
1158         // FIXME: perhaps this could be less conservative?
1159         if (childLayer->compositingState() != NotComposited)
1160             return false;
1161         // FIXME: Deal with z-index.
1162         if (!childStyle->hasAutoZIndex())
1163             return false;
1164         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1165             return false;
1166         if (childBox->hasOverflowClip() && childStyle->hasBorderRadius())
1167             return false;
1168     }
1169     return true;
1170 }
1171
1172 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1173 {
1174     if (!maxDepthToTest)
1175         return false;
1176     for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1177         if (!child->isBox())
1178             continue;
1179         RenderBox* childBox = toRenderBox(child);
1180         if (!isCandidateForOpaquenessTest(childBox))
1181             continue;
1182         LayoutPoint childLocation = childBox->location();
1183         if (childBox->isRelPositioned())
1184             childLocation.move(childBox->relativePositionOffset());
1185         LayoutRect childLocalRect = localRect;
1186         childLocalRect.moveBy(-childLocation);
1187         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1188             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1189             if (childBox->style()->position() == StaticPosition)
1190                 return false;
1191             continue;
1192         }
1193         if (childLocalRect.maxY() > childBox->height() || childLocalRect.maxX() > childBox->width())
1194             continue;
1195         if (childBox->backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1196             return true;
1197         if (childBox->foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1198             return true;
1199     }
1200     return false;
1201 }
1202
1203 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1204 {
1205     // Test to see if the children trivially obscure the background.
1206     // FIXME: This test can be much more comprehensive.
1207     if (!hasBackground())
1208         return false;
1209     // Table and root background painting is special.
1210     if (isTable() || isDocumentElement())
1211         return false;
1212     // FIXME: box-shadow is painted while background painting.
1213     if (style()->boxShadow())
1214         return false;
1215     LayoutRect backgroundRect;
1216     if (!getBackgroundPaintedExtent(backgroundRect))
1217         return false;
1218     return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1219 }
1220
1221 bool RenderBox::backgroundHasOpaqueTopLayer() const
1222 {
1223     const FillLayer& fillLayer = style()->backgroundLayers();
1224     if (fillLayer.clip() != BorderFillBox)
1225         return false;
1226
1227     // Clipped with local scrolling
1228     if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment)
1229         return false;
1230
1231     if (fillLayer.hasOpaqueImage(this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(*this, style()->effectiveZoom()))
1232         return true;
1233
1234     // If there is only one layer and no image, check whether the background color is opaque
1235     if (!fillLayer.next() && !fillLayer.hasImage()) {
1236         Color bgColor = resolveColor(CSSPropertyBackgroundColor);
1237         if (bgColor.alpha() == 255)
1238             return true;
1239     }
1240
1241     return false;
1242 }
1243
1244 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1245 {
1246     BoxPainter(*this).paintMask(paintInfo, paintOffset);
1247 }
1248
1249 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1250 {
1251     BoxPainter(*this).paintClippingMask(paintInfo, paintOffset);
1252 }
1253
1254 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1255 {
1256     if (!parent())
1257         return;
1258
1259     AllowPaintInvalidationScope scoper(frameView());
1260
1261     if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1262         (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1263         setShouldDoFullPaintInvalidation(true);
1264         return;
1265     }
1266
1267     ShapeValue* shapeOutsideValue = style()->shapeOutside();
1268     if (!frameView()->isInPerformLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1269         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1270         markShapeOutsideDependentsForLayout();
1271     }
1272
1273     if (!paintInvalidationLayerRectsForImage(image, style()->backgroundLayers(), true))
1274         paintInvalidationLayerRectsForImage(image, style()->maskLayers(), false);
1275 }
1276
1277 bool RenderBox::paintInvalidationLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
1278 {
1279     for (const FillLayer* curLayer = &layers; curLayer; curLayer = curLayer->next()) {
1280         if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(*this, style()->effectiveZoom())) {
1281             setShouldDoFullPaintInvalidation(true);
1282             return true;
1283         }
1284     }
1285     return false;
1286 }
1287
1288 InvalidationReason RenderBox::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)
1289 {
1290     // If we are set to do a full paint invalidation that means the RenderView will be
1291     // issue paint invalidations. We can then skip issuing of paint invalidations for the child
1292     // renderers as they'll be covered by the RenderView.
1293     if (!view()->doingFullPaintInvalidation()) {
1294         if ((onlyNeededPositionedMovementLayout() && compositingState() != PaintsIntoOwnBacking)
1295             || (shouldDoFullPaintInvalidationIfSelfPaintingLayer()
1296                 && hasLayer()
1297                 && layer()->isSelfPaintingLayer())) {
1298             setShouldDoFullPaintInvalidation(true, MarkOnlyThis);
1299         }
1300     }
1301
1302     InvalidationReason reason = RenderBoxModelObject::invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);
1303
1304     if (!view()->doingFullPaintInvalidation()) {
1305         if (reason == InvalidationNone || reason == InvalidationIncremental)
1306             invalidatePaintForOverflowIfNeeded();
1307
1308         // Issue paint invalidations for any scrollbars if there is a scrollable area for this renderer.
1309         if (ScrollableArea* area = scrollableArea()) {
1310             if (area->hasVerticalBarDamage())
1311                 invalidatePaintRectangle(area->verticalBarDamage());
1312             if (area->hasHorizontalBarDamage())
1313                 invalidatePaintRectangle(area->horizontalBarDamage());
1314         }
1315     }
1316
1317     // This is for the next invalidatePaintIfNeeded so must be at the end.
1318     savePreviousBorderBoxSizeIfNeeded();
1319     return reason;
1320 }
1321
1322 void RenderBox::clearPaintInvalidationState(const PaintInvalidationState& paintInvalidationState)
1323 {
1324     RenderBoxModelObject::clearPaintInvalidationState(paintInvalidationState);
1325
1326     if (ScrollableArea* area = scrollableArea())
1327         area->resetScrollbarDamage();
1328 }
1329
1330 #if ENABLE(ASSERT)
1331 bool RenderBox::paintInvalidationStateIsDirty() const
1332 {
1333     if (ScrollableArea* area = scrollableArea()) {
1334         if (area->hasVerticalBarDamage() || area->hasHorizontalBarDamage())
1335             return true;
1336     }
1337     return RenderBoxModelObject::paintInvalidationStateIsDirty();
1338 }
1339 #endif
1340
1341 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset, ContentsClipBehavior contentsClipBehavior)
1342 {
1343     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1344         return false;
1345
1346     bool isControlClip = hasControlClip();
1347     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1348
1349     if (!isControlClip && !isOverflowClip)
1350         return false;
1351
1352     LayoutRect clipRect = isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset);
1353     RoundedRect clipRoundedRect(0, 0, 0, 0);
1354     bool hasBorderRadius = style()->hasBorderRadius();
1355     if (hasBorderRadius)
1356         clipRoundedRect = style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size()));
1357
1358     if (contentsClipBehavior == SkipContentsClipIfPossible) {
1359         LayoutRect contentsVisualOverflow = contentsVisualOverflowRect();
1360         if (contentsVisualOverflow.isEmpty())
1361             return false;
1362
1363         LayoutRect conservativeClipRect = clipRect;
1364         if (hasBorderRadius)
1365             conservativeClipRect.intersect(clipRoundedRect.radiusCenterRect());
1366         conservativeClipRect.moveBy(-accumulatedOffset);
1367         if (hasLayer())
1368             conservativeClipRect.move(scrolledContentOffset());
1369         if (conservativeClipRect.contains(contentsVisualOverflow))
1370             return false;
1371     }
1372
1373     if (paintInfo.phase == PaintPhaseOutline)
1374         paintInfo.phase = PaintPhaseChildOutlines;
1375     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1376         paintInfo.phase = PaintPhaseBlockBackground;
1377         paintObject(paintInfo, accumulatedOffset);
1378         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1379     }
1380     paintInfo.context->save();
1381     if (hasBorderRadius)
1382         paintInfo.context->clipRoundedRect(clipRoundedRect);
1383     paintInfo.context->clip(pixelSnappedIntRect(clipRect));
1384     return true;
1385 }
1386
1387 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1388 {
1389     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1390
1391     paintInfo.context->restore();
1392     if (originalPhase == PaintPhaseOutline) {
1393         paintInfo.phase = PaintPhaseSelfOutline;
1394         paintObject(paintInfo, accumulatedOffset);
1395         paintInfo.phase = originalPhase;
1396     } else if (originalPhase == PaintPhaseChildBlockBackground)
1397         paintInfo.phase = originalPhase;
1398 }
1399
1400 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
1401 {
1402     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1403     // here.
1404     LayoutRect clipRect = borderBoxRect();
1405     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1406     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1407
1408     if (!hasOverflowClip())
1409         return clipRect;
1410
1411     // Subtract out scrollbars if we have them.
1412     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1413         clipRect.move(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), 0);
1414     clipRect.contract(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), layer()->scrollableArea()->horizontalScrollbarHeight(relevancy));
1415
1416     return clipRect;
1417 }
1418
1419 LayoutRect RenderBox::clipRect(const LayoutPoint& location)
1420 {
1421     LayoutRect borderBoxRect = this->borderBoxRect();
1422     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1423
1424     if (!style()->clipLeft().isAuto()) {
1425         LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width());
1426         clipRect.move(c, 0);
1427         clipRect.contract(c, 0);
1428     }
1429
1430     if (!style()->clipRight().isAuto())
1431         clipRect.contract(width() - valueForLength(style()->clipRight(), width()), 0);
1432
1433     if (!style()->clipTop().isAuto()) {
1434         LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height());
1435         clipRect.move(0, c);
1436         clipRect.contract(0, c);
1437     }
1438
1439     if (!style()->clipBottom().isAuto())
1440         clipRect.contract(0, height() - valueForLength(style()->clipBottom(), height()));
1441
1442     return clipRect;
1443 }
1444
1445 static LayoutUnit portionOfMarginNotConsumedByFloat(LayoutUnit childMargin, LayoutUnit contentSide, LayoutUnit offset)
1446 {
1447     if (childMargin <= 0)
1448         return 0;
1449     LayoutUnit contentSideWithMargin = contentSide + childMargin;
1450     if (offset > contentSideWithMargin)
1451         return childMargin;
1452     return offset - contentSide;
1453 }
1454
1455 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const
1456 {
1457     LayoutUnit logicalTopPosition = logicalTop();
1458     LayoutUnit startOffsetForContent = cb->startOffsetForContent();
1459     LayoutUnit endOffsetForContent = cb->endOffsetForContent();
1460     LayoutUnit startOffsetForLine = cb->startOffsetForLine(logicalTopPosition, false);
1461     LayoutUnit endOffsetForLine = cb->endOffsetForLine(logicalTopPosition, false);
1462
1463     // If there aren't any floats constraining us then allow the margins to shrink/expand the width as much as they want.
1464     if (startOffsetForContent == startOffsetForLine && endOffsetForContent == endOffsetForLine)
1465         return cb->availableLogicalWidthForLine(logicalTopPosition, false) - childMarginStart - childMarginEnd;
1466
1467     LayoutUnit width = cb->availableLogicalWidthForLine(logicalTopPosition, false) - std::max<LayoutUnit>(0, childMarginStart) - std::max<LayoutUnit>(0, childMarginEnd);
1468     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1469     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1470     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1471     // doesn't fit, we can use the line offset, but we need to grow it by the margin to reflect the fact that the margin was
1472     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1473     width += portionOfMarginNotConsumedByFloat(childMarginStart, startOffsetForContent, startOffsetForLine);
1474     width += portionOfMarginNotConsumedByFloat(childMarginEnd, endOffsetForContent, endOffsetForLine);
1475     return width;
1476 }
1477
1478 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1479 {
1480     if (hasOverrideContainingBlockLogicalWidth())
1481         return overrideContainingBlockContentLogicalWidth();
1482
1483     RenderBlock* cb = containingBlock();
1484     return cb->availableLogicalWidth();
1485 }
1486
1487 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1488 {
1489     if (hasOverrideContainingBlockLogicalHeight())
1490         return overrideContainingBlockContentLogicalHeight();
1491
1492     RenderBlock* cb = containingBlock();
1493     return cb->availableLogicalHeight(heightType);
1494 }
1495
1496 LayoutUnit RenderBox::containingBlockAvailableLineWidth() const
1497 {
1498     RenderBlock* cb = containingBlock();
1499     if (cb->isRenderBlockFlow())
1500         return toRenderBlockFlow(cb)->availableLogicalWidthForLine(logicalTop(), false, availableLogicalHeight(IncludeMarginBorderPadding));
1501     return 0;
1502 }
1503
1504 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1505 {
1506     if (hasOverrideContainingBlockLogicalHeight())
1507         return overrideContainingBlockContentLogicalHeight();
1508
1509     RenderBlock* cb = containingBlock();
1510     if (cb->hasOverrideHeight())
1511         return cb->overrideLogicalContentHeight();
1512
1513     RenderStyle* containingBlockStyle = cb->style();
1514     Length logicalHeightLength = containingBlockStyle->logicalHeight();
1515
1516     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1517     if (!logicalHeightLength.isFixed()) {
1518         LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode()
1519             ? view()->frameView()->unscaledVisibleContentSize().height()
1520             : view()->frameView()->unscaledVisibleContentSize().width();
1521         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1522         return std::min(fillAvailableExtent, fillFallbackExtent);
1523     }
1524
1525     // Use the content box logical height as specified by the style.
1526     return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1527 }
1528
1529 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
1530 {
1531     if (paintInvalidationContainer == this)
1532         return;
1533
1534     if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer)) {
1535         LayoutSize offset = paintInvalidationState->paintOffset() + locationOffset();
1536         if (style()->hasInFlowPosition() && layer())
1537             offset += layer()->offsetForInFlowPosition();
1538         transformState.move(offset);
1539         return;
1540     }
1541
1542     bool containerSkipped;
1543     RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
1544     if (!o)
1545         return;
1546
1547     bool isFixedPos = style()->position() == FixedPosition;
1548     bool hasTransform = hasLayer() && layer()->transform();
1549     // If this box has a transform, it acts as a fixed position container for fixed descendants,
1550     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1551     if (hasTransform && !isFixedPos)
1552         mode &= ~IsFixed;
1553     else if (isFixedPos)
1554         mode |= IsFixed;
1555
1556     if (wasFixed)
1557         *wasFixed = mode & IsFixed;
1558
1559     LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1560
1561     bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
1562     if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
1563         TransformationMatrix t;
1564         getTransformFromContainer(o, containerOffset, t);
1565         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1566     } else
1567         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1568
1569     if (containerSkipped) {
1570         // There can't be a transform between paintInvalidationContainer and o, because transforms create containers, so it should be safe
1571         // to just subtract the delta between the paintInvalidationContainer and o.
1572         LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
1573         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1574         return;
1575     }
1576
1577     mode &= ~ApplyContainerFlip;
1578
1579     o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed);
1580 }
1581
1582 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1583 {
1584     bool isFixedPos = style()->position() == FixedPosition;
1585     bool hasTransform = hasLayer() && layer()->transform();
1586     if (hasTransform && !isFixedPos) {
1587         // If this box has a transform, it acts as a fixed position container for fixed descendants,
1588         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1589         mode &= ~IsFixed;
1590     } else if (isFixedPos)
1591         mode |= IsFixed;
1592
1593     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
1594 }
1595
1596 LayoutSize RenderBox::offsetFromContainer(const RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
1597 {
1598     ASSERT(o == container());
1599
1600     LayoutSize offset;
1601     if (isRelPositioned())
1602         offset += offsetForInFlowPosition();
1603
1604     if (!isInline() || isReplaced()) {
1605         if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
1606             const RenderBlock* block = toRenderBlock(o);
1607             LayoutRect columnRect(frameRect());
1608             block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1609             offset += toSize(columnRect.location());
1610             LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1611             offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset)));
1612             offset += o->columnOffset(columnPoint);
1613             offset = block->flipForWritingMode(offset);
1614
1615             if (offsetDependsOnPoint)
1616                 *offsetDependsOnPoint = true;
1617         } else {
1618             offset += topLeftLocationOffset();
1619             if (o->isRenderFlowThread()) {
1620                 // So far the point has been in flow thread coordinates (i.e. as if everything in
1621                 // the fragmentation context lived in one tall single column). Convert it to a
1622                 // visual point now.
1623                 LayoutPoint pointInContainer = point + offset;
1624                 offset += o->columnOffset(pointInContainer);
1625                 if (offsetDependsOnPoint)
1626                     *offsetDependsOnPoint = true;
1627             }
1628         }
1629     }
1630
1631     if (o->hasOverflowClip())
1632         offset -= toRenderBox(o)->scrolledContentOffset();
1633
1634     if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1635         offset += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
1636
1637     return offset;
1638 }
1639
1640 InlineBox* RenderBox::createInlineBox()
1641 {
1642     return new InlineBox(*this);
1643 }
1644
1645 void RenderBox::dirtyLineBoxes(bool fullLayout)
1646 {
1647     if (inlineBoxWrapper()) {
1648         if (fullLayout) {
1649             inlineBoxWrapper()->destroy();
1650             ASSERT(m_rareData);
1651             m_rareData->m_inlineBoxWrapper = 0;
1652         } else {
1653             inlineBoxWrapper()->dirtyLineBoxes();
1654         }
1655     }
1656 }
1657
1658 void RenderBox::positionLineBox(InlineBox* box)
1659 {
1660     if (isOutOfFlowPositioned()) {
1661         // Cache the x position only if we were an INLINE type originally.
1662         bool wasInline = style()->isOriginalDisplayInlineType();
1663         if (wasInline) {
1664             // The value is cached in the xPos of the box.  We only need this value if
1665             // our object was inline originally, since otherwise it would have ended up underneath
1666             // the inlines.
1667             RootInlineBox& root = box->root();
1668             root.block().setStaticInlinePositionForChild(this, LayoutUnit::fromFloatRound(box->logicalLeft()));
1669             if (style()->hasStaticInlinePosition(box->isHorizontal()))
1670                 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1671         } else {
1672             // Our object was a block originally, so we make our normal flow position be
1673             // just below the line box (as though all the inlines that came before us got
1674             // wrapped in an anonymous block, which is what would have happened had we been
1675             // in flow).  This value was cached in the y() of the box.
1676             layer()->setStaticBlockPosition(box->logicalTop());
1677             if (style()->hasStaticBlockPosition(box->isHorizontal()))
1678                 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1679         }
1680
1681         if (container()->isRenderInline())
1682             moveWithEdgeOfInlineContainerIfNecessary(box->isHorizontal());
1683
1684         // Nuke the box.
1685         box->remove(DontMarkLineBoxes);
1686         box->destroy();
1687     } else if (isReplaced()) {
1688         setLocation(roundedLayoutPoint(box->topLeft()));
1689         setInlineBoxWrapper(box);
1690     }
1691 }
1692
1693 void RenderBox::moveWithEdgeOfInlineContainerIfNecessary(bool isHorizontal)
1694 {
1695     ASSERT(isOutOfFlowPositioned() && container()->isRenderInline() && container()->isRelPositioned());
1696     // If this object is inside a relative positioned inline and its inline position is an explicit offset from the edge of its container
1697     // then it will need to move if its inline container has changed width. We do not track if the width has changed
1698     // but if we are here then we are laying out lines inside it, so it probably has - mark our object for layout so that it can
1699     // move to the new offset created by the new width.
1700     if (!normalChildNeedsLayout() && !style()->hasStaticInlinePosition(isHorizontal))
1701         setChildNeedsLayout(MarkOnlyThis);
1702 }
1703
1704 void RenderBox::deleteLineBoxWrapper()
1705 {
1706     if (inlineBoxWrapper()) {
1707         if (!documentBeingDestroyed())
1708             inlineBoxWrapper()->remove();
1709         inlineBoxWrapper()->destroy();
1710         ASSERT(m_rareData);
1711         m_rareData->m_inlineBoxWrapper = 0;
1712     }
1713 }
1714
1715 LayoutRect RenderBox::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1716 {
1717     if (style()->visibility() != VISIBLE) {
1718         RenderLayer* layer = enclosingLayer();
1719         layer->updateDescendantDependentFlags();
1720         if (layer->subtreeIsInvisible())
1721             return LayoutRect();
1722     }
1723
1724     LayoutRect r = visualOverflowRect();
1725     mapRectToPaintInvalidationBacking(paintInvalidationContainer, r, paintInvalidationState);
1726     return r;
1727 }
1728
1729 void RenderBox::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, const PaintInvalidationState* paintInvalidationState) const
1730 {
1731     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1732     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1733     // offset corner for the enclosing container). This allows for a fully RL or BT document to issue paint invalidations
1734     // properly even during layout, since the rect remains flipped all the way until the end.
1735     //
1736     // RenderView::computeRectForPaintInvalidation then converts the rect to physical coordinates. We also convert to
1737     // physical when we hit a paintInvalidationContainer boundary. Therefore the final rect returned is always in the
1738     // physical coordinate space of the paintInvalidationContainer.
1739     RenderStyle* styleToUse = style();
1740
1741     EPosition position = styleToUse->position();
1742
1743     // We need to inflate the paint invalidation rect before we use paintInvalidationState,
1744     // else we would forget to inflate it for the current renderer. FIXME: If these were
1745     // included into the visual overflow for repaint, we wouldn't have this issue.
1746     inflatePaintInvalidationRectForReflectionAndFilter(rect);
1747
1748     if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer) && position != FixedPosition) {
1749         if (layer() && layer()->transform())
1750             rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
1751
1752         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
1753         if (styleToUse->hasInFlowPosition() && layer())
1754             rect.move(layer()->offsetForInFlowPosition());
1755
1756         rect.moveBy(location());
1757         rect.move(paintInvalidationState->paintOffset());
1758         if (paintInvalidationState->isClipped())
1759             rect.intersect(paintInvalidationState->clipRect());
1760         return;
1761     }
1762
1763     if (paintInvalidationContainer == this) {
1764         if (paintInvalidationContainer->style()->isFlippedBlocksWritingMode())
1765             flipForWritingMode(rect);
1766         return;
1767     }
1768
1769     bool containerSkipped;
1770     RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
1771     if (!o)
1772         return;
1773
1774     if (isWritingModeRoot())
1775         flipForWritingMode(rect);
1776
1777     LayoutPoint topLeft = rect.location();
1778     topLeft.move(locationOffset());
1779
1780     // We are now in our parent container's coordinate space.  Apply our transform to obtain a bounding box
1781     // in the parent's coordinate space that encloses us.
1782     if (hasLayer() && layer()->transform()) {
1783         rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
1784         topLeft = rect.location();
1785         topLeft.move(locationOffset());
1786     }
1787
1788     if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline()) {
1789         topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
1790     } else if (styleToUse->hasInFlowPosition() && layer()) {
1791         // Apply the relative position offset when invalidating a rectangle.  The layer
1792         // is translated, but the render box isn't, so we need to do this to get the
1793         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
1794         // flag on the RenderObject has been cleared, so use the one on the style().
1795         topLeft += layer()->offsetForInFlowPosition();
1796     }
1797
1798     if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) {
1799         LayoutRect paintInvalidationRect(topLeft, rect.size());
1800         toRenderBlock(o)->adjustRectForColumns(paintInvalidationRect);
1801         topLeft = paintInvalidationRect.location();
1802         rect = paintInvalidationRect;
1803     }
1804
1805     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1806     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1807     rect.setLocation(topLeft);
1808     if (o->hasOverflowClip()) {
1809         RenderBox* containerBox = toRenderBox(o);
1810         containerBox->applyCachedClipAndScrollOffsetForPaintInvalidation(rect);
1811         if (rect.isEmpty())
1812             return;
1813     }
1814
1815     if (containerSkipped) {
1816         // If the paintInvalidationContainer is below o, then we need to map the rect into paintInvalidationContainer's coordinates.
1817         LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
1818         rect.move(-containerOffset);
1819         return;
1820     }
1821
1822     if (o->isRenderView())
1823         toRenderView(o)->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, position == FixedPosition ? RenderView::IsFixedPosition : RenderView::IsNotFixedPosition, paintInvalidationState);
1824     else
1825         o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
1826 }
1827
1828 void RenderBox::inflatePaintInvalidationRectForReflectionAndFilter(LayoutRect& paintInvalidationRect) const
1829 {
1830     if (hasReflection())
1831         paintInvalidationRect.unite(reflectedRect(paintInvalidationRect));
1832
1833     if (style()->hasFilter())
1834         style()->filterOutsets().expandRect(paintInvalidationRect);
1835 }
1836
1837 void RenderBox::invalidatePaintForOverhangingFloats(bool)
1838 {
1839 }
1840
1841 void RenderBox::updateLogicalWidth()
1842 {
1843     LogicalExtentComputedValues computedValues;
1844     computeLogicalWidth(computedValues);
1845
1846     setLogicalWidth(computedValues.m_extent);
1847     setLogicalLeft(computedValues.m_position);
1848     setMarginStart(computedValues.m_margins.m_start);
1849     setMarginEnd(computedValues.m_margins.m_end);
1850 }
1851
1852 static float getMaxWidthListMarker(const RenderBox* renderer)
1853 {
1854 #if ENABLE(ASSERT)
1855     ASSERT(renderer);
1856     Node* parentNode = renderer->generatingNode();
1857     ASSERT(parentNode);
1858     ASSERT(isHTMLOListElement(parentNode) || isHTMLUListElement(parentNode));
1859     ASSERT(renderer->style()->textAutosizingMultiplier() != 1);
1860 #endif
1861     float maxWidth = 0;
1862     for (RenderObject* child = renderer->slowFirstChild(); child; child = child->nextSibling()) {
1863         if (!child->isListItem())
1864             continue;
1865
1866         RenderBox* listItem = toRenderBox(child);
1867         for (RenderObject* itemChild = listItem->slowFirstChild(); itemChild; itemChild = itemChild->nextSibling()) {
1868             if (!itemChild->isListMarker())
1869                 continue;
1870             RenderBox* itemMarker = toRenderBox(itemChild);
1871             // Make sure to compute the autosized width.
1872             if (itemMarker->needsLayout())
1873                 itemMarker->layout();
1874             maxWidth = std::max<float>(maxWidth, toRenderListMarker(itemMarker)->logicalWidth().toFloat());
1875             break;
1876         }
1877     }
1878     return maxWidth;
1879 }
1880
1881 void RenderBox::computeLogicalWidth(LogicalExtentComputedValues& computedValues) const
1882 {
1883     computedValues.m_extent = logicalWidth();
1884     computedValues.m_position = logicalLeft();
1885     computedValues.m_margins.m_start = marginStart();
1886     computedValues.m_margins.m_end = marginEnd();
1887
1888     if (isOutOfFlowPositioned()) {
1889         // FIXME: This calculation is not patched for block-flow yet.
1890         // https://bugs.webkit.org/show_bug.cgi?id=46500
1891         computePositionedLogicalWidth(computedValues);
1892         return;
1893     }
1894
1895     // If layout is limited to a subtree, the subtree root's logical width does not change.
1896     if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1897         return;
1898
1899     // The parent box is flexing us, so it has increased or decreased our
1900     // width.  Use the width from the style context.
1901     // FIXME: Account for block-flow in flexible boxes.
1902     // https://bugs.webkit.org/show_bug.cgi?id=46418
1903     if (hasOverrideWidth() && (style()->borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
1904         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
1905         return;
1906     }
1907
1908     // FIXME: Account for block-flow in flexible boxes.
1909     // https://bugs.webkit.org/show_bug.cgi?id=46418
1910     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1911     bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1912     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1913
1914     RenderStyle* styleToUse = style();
1915     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
1916
1917     RenderBlock* cb = containingBlock();
1918     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContent());
1919     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1920
1921     if (isInline() && !isInlineBlockOrInlineTable()) {
1922         // just calculate margins
1923         computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
1924         computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
1925         if (treatAsReplaced)
1926             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
1927         return;
1928     }
1929
1930     // Width calculations
1931     if (treatAsReplaced)
1932         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
1933     else {
1934         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1935         if (hasPerpendicularContainingBlock)
1936             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1937         LayoutUnit preferredWidth = computeLogicalWidthUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb);
1938         computedValues.m_extent = constrainLogicalWidthByMinMax(preferredWidth, containerWidthInInlineDirection, cb);
1939     }
1940
1941     // Margin calculations.
1942     computeMarginsForDirection(InlineDirection, cb, containerLogicalWidth, computedValues.m_extent, computedValues.m_margins.m_start,
1943         computedValues.m_margins.m_end, style()->marginStart(), style()->marginEnd());
1944
1945     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
1946         && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated() && !cb->isRenderGrid()) {
1947         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(this);
1948         bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
1949         if (hasInvertedDirection)
1950             computedValues.m_margins.m_start = newMargin;
1951         else
1952             computedValues.m_margins.m_end = newMargin;
1953     }
1954
1955     if (styleToUse->textAutosizingMultiplier() != 1 && styleToUse->marginStart().type() == Fixed) {
1956         Node* parentNode = generatingNode();
1957         if (parentNode && (isHTMLOListElement(*parentNode) || isHTMLUListElement(*parentNode))) {
1958             // Make sure the markers in a list are properly positioned (i.e. not chopped off) when autosized.
1959             const float adjustedMargin = (1 - 1.0 / styleToUse->textAutosizingMultiplier()) * getMaxWidthListMarker(this);
1960             bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
1961             if (hasInvertedDirection)
1962                 computedValues.m_margins.m_end += adjustedMargin;
1963             else
1964                 computedValues.m_margins.m_start += adjustedMargin;
1965         }
1966     }
1967 }
1968
1969 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
1970 {
1971     LayoutUnit marginStart = 0;
1972     LayoutUnit marginEnd = 0;
1973     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
1974 }
1975
1976 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
1977 {
1978     marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
1979     marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
1980     return availableLogicalWidth - marginStart - marginEnd;
1981 }
1982
1983 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(const Length& logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
1984 {
1985     if (logicalWidthLength.type() == FillAvailable)
1986         return fillAvailableMeasure(availableLogicalWidth);
1987
1988     LayoutUnit minLogicalWidth = 0;
1989     LayoutUnit maxLogicalWidth = 0;
1990     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
1991
1992     if (logicalWidthLength.type() == MinContent)
1993         return minLogicalWidth + borderAndPadding;
1994
1995     if (logicalWidthLength.type() == MaxContent)
1996         return maxLogicalWidth + borderAndPadding;
1997
1998     if (logicalWidthLength.type() == FitContent) {
1999         minLogicalWidth += borderAndPadding;
2000         maxLogicalWidth += borderAndPadding;
2001         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2002     }
2003
2004     ASSERT_NOT_REACHED();
2005     return 0;
2006 }
2007
2008 LayoutUnit RenderBox::computeLogicalWidthUsing(SizeType widthType, const Length& logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* cb) const
2009 {
2010     if (!logicalWidth.isIntrinsicOrAuto()) {
2011         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2012         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2013     }
2014
2015     if (logicalWidth.isIntrinsic())
2016         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2017
2018     LayoutUnit marginStart = 0;
2019     LayoutUnit marginEnd = 0;
2020     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2021
2022     if (shrinkToAvoidFloats() && cb->isRenderBlockFlow() && toRenderBlockFlow(cb)->containsFloats())
2023         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb)));
2024
2025     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(logicalWidth))
2026         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2027     return logicalWidthResult;
2028 }
2029
2030 static bool flexItemHasStretchAlignment(const RenderObject* flexitem)
2031 {
2032     RenderObject* parent = flexitem->parent();
2033     // auto margins mean we don't stretch.
2034     if (parent->style()->isColumnFlexDirection()) {
2035         if (flexitem->style()->marginStart().isAuto() || flexitem->style()->marginEnd().isAuto())
2036             return false;
2037     } else {
2038         if (flexitem->style()->marginBefore().isAuto() || flexitem->style()->marginAfter().isAuto())
2039             return false;
2040     }
2041     return flexitem->style()->alignSelf() == ItemPositionStretch || (flexitem->style()->alignSelf() == ItemPositionAuto && parent->style()->alignItems() == ItemPositionStretch);
2042 }
2043
2044 static bool isStretchingColumnFlexItem(const RenderObject* flexitem)
2045 {
2046     RenderObject* parent = flexitem->parent();
2047     if (parent->isDeprecatedFlexibleBox() && parent->style()->boxOrient() == VERTICAL && parent->style()->boxAlign() == BSTRETCH)
2048         return true;
2049
2050     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2051     if (parent->isFlexibleBox() && parent->style()->flexWrap() == FlexNoWrap && parent->style()->isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2052         return true;
2053     return false;
2054 }
2055
2056 bool RenderBox::sizesLogicalWidthToFitContent(const Length& logicalWidth) const
2057 {
2058     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2059     // but they allow text to sit on the same line as the marquee.
2060     if (isFloating() || (isInlineBlockOrInlineTable() && !isMarquee()))
2061         return true;
2062
2063     if (logicalWidth.type() == Intrinsic)
2064         return true;
2065
2066     // Children of a horizontal marquee do not fill the container by default.
2067     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2068     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2069     // block-flow (as well as how marquee overflow should relate to block flow).
2070     // https://bugs.webkit.org/show_bug.cgi?id=46472
2071     if (parent()->isMarquee()) {
2072         EMarqueeDirection dir = parent()->style()->marqueeDirection();
2073         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2074             return true;
2075     }
2076
2077     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2078     // In the case of columns that have a stretch alignment, we go ahead and layout at the
2079     // stretched size to avoid an extra layout when applying alignment.
2080     if (parent()->isFlexibleBox()) {
2081         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2082         if (!parent()->style()->isColumnFlexDirection() || parent()->style()->flexWrap() != FlexNoWrap)
2083             return true;
2084         if (!flexItemHasStretchAlignment(this))
2085             return true;
2086     }
2087
2088     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2089     // that don't stretch their kids lay out their children at their intrinsic widths.
2090     // FIXME: Think about block-flow here.
2091     // https://bugs.webkit.org/show_bug.cgi?id=46473
2092     if (parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
2093         return true;
2094
2095     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2096     // stretching column flexbox.
2097     // FIXME: Think about block-flow here.
2098     // https://bugs.webkit.org/show_bug.cgi?id=46473
2099     if (logicalWidth.isAuto() && !isStretchingColumnFlexItem(this) && autoWidthShouldFitContent())
2100         return true;
2101
2102     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2103         return true;
2104
2105     return false;
2106 }
2107
2108 bool RenderBox::autoWidthShouldFitContent() const
2109 {
2110     return node() && (isHTMLInputElement(*node()) || isHTMLSelectElement(*node()) || isHTMLButtonElement(*node())
2111         || isHTMLTextAreaElement(*node()) || (isHTMLLegendElement(*node()) && !style()->hasOutOfFlowPosition()));
2112 }
2113
2114 void RenderBox::computeMarginsForDirection(MarginDirection flowDirection, const RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd, Length marginStartLength, Length marginEndLength) const
2115 {
2116     if (flowDirection == BlockDirection || isFloating() || isInline()) {
2117         if (isTableCell() && flowDirection == BlockDirection) {
2118             // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2119             // we may just do it with an extra anonymous block inside the cell.
2120             marginStart = 0;
2121             marginEnd = 0;
2122             return;
2123         }
2124
2125         // Margins are calculated with respect to the logical width of
2126         // the containing block (8.3)
2127         // Inline blocks/tables and floats don't have their margins increased.
2128         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2129         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2130         return;
2131     }
2132
2133     if (containingBlock->isFlexibleBox()) {
2134         // We need to let flexbox handle the margin adjustment - otherwise, flexbox
2135         // will think we're wider than we actually are and calculate line sizes wrong.
2136         // See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
2137         if (marginStartLength.isAuto())
2138             marginStartLength.setValue(0);
2139         if (marginEndLength.isAuto())
2140             marginEndLength.setValue(0);
2141     }
2142
2143     LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2144     LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2145
2146     LayoutUnit availableWidth = containerWidth;
2147     if (avoidsFloats() && containingBlock->isRenderBlockFlow() && toRenderBlockFlow(containingBlock)->containsFloats()) {
2148         availableWidth = containingBlockAvailableLineWidth();
2149         if (shrinkToAvoidFloats() && availableWidth < containerWidth) {
2150             marginStart = std::max<LayoutUnit>(0, marginStartWidth);
2151             marginEnd = std::max<LayoutUnit>(0, marginEndWidth);
2152         }
2153     }
2154
2155     // CSS 2.1 (10.3.3): "If 'width' is not 'auto' and 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width'
2156     // (plus any of 'margin-left' or 'margin-right' that are not 'auto') is larger than the width of the containing block, then any 'auto'
2157     // values for 'margin-left' or 'margin-right' are, for the following rules, treated as zero.
2158     LayoutUnit marginBoxWidth = childWidth + (!style()->width().isAuto() ? marginStartWidth + marginEndWidth : LayoutUnit());
2159
2160     // CSS 2.1: "If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element
2161     // with respect to the edges of the containing block."
2162     const RenderStyle* containingBlockStyle = containingBlock->style();
2163     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && marginBoxWidth < availableWidth)
2164         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlockStyle->textAlign() == WEBKIT_CENTER)) {
2165         // Other browsers center the margin box for align=center elements so we match them here.
2166         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (availableWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2167         marginStart = centeredMarginBoxStart + marginStartWidth;
2168         marginEnd = availableWidth - childWidth - marginStart + marginEndWidth;
2169         return;
2170     }
2171
2172     // CSS 2.1: "If there is exactly one value specified as 'auto', its used value follows from the equality."
2173     if (marginEndLength.isAuto() && marginBoxWidth < availableWidth) {
2174         marginStart = marginStartWidth;
2175         marginEnd = availableWidth - childWidth - marginStart;
2176         return;
2177     }
2178
2179     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
2180         || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
2181     if ((marginStartLength.isAuto() && marginBoxWidth < availableWidth) || pushToEndFromTextAlign) {
2182         marginEnd = marginEndWidth;
2183         marginStart = availableWidth - childWidth - marginEnd;
2184         return;
2185     }
2186
2187     // Either no auto margins, or our margin box width is >= the container width, auto margins will just turn into 0.
2188     marginStart = marginStartWidth;
2189     marginEnd = marginEndWidth;
2190 }
2191
2192 void RenderBox::updateLogicalHeight()
2193 {
2194     m_intrinsicContentLogicalHeight = contentLogicalHeight();
2195
2196     LogicalExtentComputedValues computedValues;
2197     computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2198
2199     setLogicalHeight(computedValues.m_extent);
2200     setLogicalTop(computedValues.m_position);
2201     setMarginBefore(computedValues.m_margins.m_before);
2202     setMarginAfter(computedValues.m_margins.m_after);
2203 }
2204
2205 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2206 {
2207     computedValues.m_extent = logicalHeight;
2208     computedValues.m_position = logicalTop;
2209
2210     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2211     if (isTableCell() || (isInline() && !isReplaced()))
2212         return;
2213
2214     Length h;
2215     if (isOutOfFlowPositioned())
2216         computePositionedLogicalHeight(computedValues);
2217     else {
2218         RenderBlock* cb = containingBlock();
2219
2220         // If we are perpendicular to our containing block then we need to resolve our block-start and block-end margins so that if they
2221         // are 'auto' we are centred or aligned within the inline flow containing block: this is done by computing the margins as though they are inline.
2222         // Note that as this is the 'sizing phase' we are using our own writing mode rather than the containing block's. We use the containing block's
2223         // writing mode when figuring out the block-direction margins for positioning in |computeAndSetBlockDirectionMargins| (i.e. margin collapsing etc.).
2224         // See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
2225         MarginDirection flowDirection = isHorizontalWritingMode() != cb->isHorizontalWritingMode() ? InlineDirection : BlockDirection;
2226
2227         // For tables, calculate margins only.
2228         if (isTable()) {
2229             computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
2230                 computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
2231             return;
2232         }
2233
2234         // FIXME: Account for block-flow in flexible boxes.
2235         // https://bugs.webkit.org/show_bug.cgi?id=46418
2236         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
2237         bool stretching = parent()->style()->boxAlign() == BSTRETCH;
2238         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2239         bool checkMinMaxHeight = false;
2240
2241         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2242         // grab our cached flexible height.
2243         // FIXME: Account for block-flow in flexible boxes.
2244         // https://bugs.webkit.org/show_bug.cgi?id=46418
2245         if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
2246             h = Length(overrideLogicalContentHeight(), Fixed);
2247         else if (treatAsReplaced)
2248             h = Length(computeReplacedLogicalHeight(), Fixed);
2249         else {
2250             h = style()->logicalHeight();
2251             checkMinMaxHeight = true;
2252         }
2253
2254         // Block children of horizontal flexible boxes fill the height of the box.
2255         // FIXME: Account for block-flow in flexible boxes.
2256         // https://bugs.webkit.org/show_bug.cgi?id=46418
2257         if (h.isAuto() && inHorizontalBox && toRenderDeprecatedFlexibleBox(parent())->isStretchingChildren()) {
2258             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2259             checkMinMaxHeight = false;
2260         }
2261
2262         LayoutUnit heightResult;
2263         if (checkMinMaxHeight) {
2264             heightResult = computeLogicalHeightUsing(style()->logicalHeight(), computedValues.m_extent - borderAndPaddingLogicalHeight());
2265             if (heightResult == -1)
2266                 heightResult = computedValues.m_extent;
2267             heightResult = constrainLogicalHeightByMinMax(heightResult, computedValues.m_extent - borderAndPaddingLogicalHeight());
2268         } else {
2269             // The only times we don't check min/max height are when a fixed length has
2270             // been given as an override.  Just use that.  The value has already been adjusted
2271             // for box-sizing.
2272             ASSERT(h.isFixed());
2273             heightResult = h.value() + borderAndPaddingLogicalHeight();
2274         }
2275
2276         computedValues.m_extent = heightResult;
2277         computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
2278             computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
2279     }
2280
2281     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2282     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2283     // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2284     // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2285     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2286     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2287         && (isDocumentElement() || (isBody() && document().documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
2288     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2289         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2290         LayoutUnit visibleHeight = view()->viewLogicalHeightForPercentages();
2291         if (isDocumentElement())
2292             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2293         else {
2294             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2295             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2296         }
2297     }
2298 }
2299
2300 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
2301 {
2302     LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
2303     if (logicalHeight != -1)
2304         logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2305     return logicalHeight;
2306 }
2307
2308 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height, LayoutUnit intrinsicContentHeight) const
2309 {
2310     LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
2311     if (heightIncludingScrollbar == -1)
2312         return -1;
2313     return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2314 }
2315
2316 LayoutUnit RenderBox::computeIntrinsicLogicalContentHeightUsing(const Length& logicalHeightLength, LayoutUnit intrinsicContentHeight, LayoutUnit borderAndPadding) const
2317 {
2318     // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
2319     // If that happens, this code will have to change.
2320     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2321         if (isReplaced())
2322             return intrinsicSize().height();
2323         if (m_intrinsicContentLogicalHeight != -1)
2324             return m_intrinsicContentLogicalHeight;
2325         return intrinsicContentHeight;
2326     }
2327     if (logicalHeightLength.isFillAvailable())
2328         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2329     ASSERT_NOT_REACHED();
2330     return 0;
2331 }
2332
2333 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
2334 {
2335     // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
2336     // If that happens, this code will have to change.
2337     if (height.isIntrinsic()) {
2338         if (intrinsicContentHeight == -1)
2339             return -1; // Intrinsic height isn't available.
2340         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2341     }
2342     if (height.isFixed())
2343         return height.value();
2344     if (height.isPercent())
2345         return computePercentageLogicalHeight(height);
2346     return -1;
2347 }
2348
2349 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const
2350 {
2351     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2352     // and percent heights of children should be resolved against the multicol or paged container.
2353     if (containingBlock->isRenderFlowThread())
2354         return true;
2355
2356     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2357     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2358     if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2359         return false;
2360     return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style()->logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2361 }
2362
2363 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2364 {
2365     LayoutUnit availableHeight = -1;
2366
2367     bool skippedAutoHeightContainingBlock = false;
2368     RenderBlock* cb = containingBlock();
2369     const RenderBox* containingBlockChild = this;
2370     LayoutUnit rootMarginBorderPaddingHeight = 0;
2371     while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) {
2372         if (cb->isBody() || cb->isDocumentElement())
2373             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2374         skippedAutoHeightContainingBlock = true;
2375         containingBlockChild = cb;
2376         cb = cb->containingBlock();
2377     }
2378     cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2379
2380     RenderStyle* cbstyle = cb->style();
2381
2382     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2383     // explicitly specified that can be used for any percentage computations.
2384     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle->logicalHeight().isAuto() || (!cbstyle->logicalTop().isAuto() && !cbstyle->logicalBottom().isAuto()));
2385
2386     bool includeBorderPadding = isTable();
2387
2388     if (isHorizontalWritingMode() != cb->isHorizontalWritingMode()) {
2389         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2390     } else if (hasOverrideContainingBlockLogicalHeight()) {
2391         availableHeight = overrideContainingBlockContentLogicalHeight();
2392     } else if (cb->isFlexItem() && flexItemHasStretchAlignment(cb) && cb->hasOverrideHeight()) {
2393         availableHeight = cb->overrideLogicalContentHeight();
2394     } else if (cb->isTableCell()) {
2395         if (!skippedAutoHeightContainingBlock) {
2396             // Table cells violate what the CSS spec says to do with heights. Basically we
2397             // don't care if the cell specified a height or not. We just always make ourselves
2398             // be a percentage of the cell's current content height.
2399             if (!cb->hasOverrideHeight()) {
2400                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2401                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2402                 // While we can't get all cases right, we can at least detect when the cell has a specified
2403                 // height or when the table has a specified height. In these cases we want to initially have
2404                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2405                 // to grow to fill the space. This could end up being wrong in some cases, but it is
2406                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2407                 RenderTableCell* cell = toRenderTableCell(cb);
2408                 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2409                     return 0;
2410                 return -1;
2411             }
2412             availableHeight = cb->overrideLogicalContentHeight();
2413             includeBorderPadding = true;
2414         }
2415     } else if (cbstyle->logicalHeight().isFixed()) {
2416         LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle->logicalHeight().value());
2417         availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), -1));
2418     } else if (cbstyle->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2419         // We need to recur and compute the percentage height for our containing block.
2420         LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle->logicalHeight());
2421         if (heightWithScrollbar != -1) {
2422             LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2423             // We need to adjust for min/max height because this method does not
2424             // handle the min/max of the current block, its caller does. So the
2425             // return value from the recursive call will not have been adjusted
2426             // yet.
2427             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
2428             availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2429         }
2430     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2431         // Don't allow this to affect the block' height() member variable, since this
2432         // can get called while the block is still laying out its kids.
2433         LogicalExtentComputedValues computedValues;
2434         cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2435         availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2436     } else if (cb->isRenderView())
2437         availableHeight = view()->viewLogicalHeightForPercentages();
2438
2439     if (availableHeight == -1)
2440         return availableHeight;
2441
2442     availableHeight -= rootMarginBorderPaddingHeight;
2443
2444     if (isTable() && isOutOfFlowPositioned())
2445         availableHeight += cb->paddingLogicalHeight();
2446
2447     LayoutUnit result = valueForLength(height, availableHeight);
2448     if (includeBorderPadding) {
2449         // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2450         // It is necessary to use the border-box to match WinIE's broken
2451         // box model. This is essential for sizing inside
2452         // table cells using percentage heights.
2453         result -= borderAndPaddingLogicalHeight();
2454         return std::max<LayoutUnit>(0, result);
2455     }
2456     return result;
2457 }
2458
2459 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2460 {
2461     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
2462 }
2463
2464 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2465 {
2466     LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMinWidth().isPercent()) || style()->logicalMinWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2467     LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMaxWidth().isPercent()) || style()->logicalMaxWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2468     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2469 }
2470
2471 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(const Length& logicalWidth) const
2472 {
2473     switch (logicalWidth.type()) {
2474         case Fixed:
2475             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2476         case MinContent:
2477         case MaxContent: {
2478             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2479             LayoutUnit availableLogicalWidth = 0;
2480             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2481         }
2482         case FitContent:
2483         case FillAvailable:
2484         case Percent:
2485         case Calculated: {
2486             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2487             // containing block's block-flow.
2488             // https://bugs.webkit.org/show_bug.cgi?id=46496
2489             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2490             Length containerLogicalWidth = containingBlock()->style()->logicalWidth();
2491             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2492             // https://bugs.webkit.org/show_bug.cgi?id=91071
2493             if (logicalWidth.isIntrinsic())
2494                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2495             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2496                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2497             return 0;
2498         }
2499         case Intrinsic:
2500         case MinIntrinsic:
2501         case Auto:
2502         case MaxSizeNone:
2503             return intrinsicLogicalWidth();
2504         case ExtendToZoom:
2505         case DeviceWidth:
2506         case DeviceHeight:
2507             break;
2508     }
2509
2510     ASSERT_NOT_REACHED();
2511     return 0;
2512 }
2513
2514 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2515 {
2516     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2517 }
2518
2519 bool RenderBox::logicalHeightComputesAsNone(SizeType sizeType) const
2520 {
2521     ASSERT(sizeType == MinSize || sizeType == MaxSize);
2522     Length logicalHeight = sizeType == MinSize ? style()->logicalMinHeight() : style()->logicalMaxHeight();
2523     Length initialLogicalHeight = sizeType == MinSize ? RenderStyle::initialMinSize() : RenderStyle::initialMaxSize();
2524
2525     if (logicalHeight == initialLogicalHeight)
2526         return true;
2527
2528     if (!logicalHeight.isPercent() || isOutOfFlowPositioned())
2529         return false;
2530
2531     // Anonymous block boxes are ignored when resolving percentage values that would refer to it:
2532     // the closest non-anonymous ancestor box is used instead.
2533     RenderBlock* containingBlock = this->containingBlock();
2534     while (containingBlock->isAnonymous())
2535         containingBlock = containingBlock->containingBlock();
2536
2537     return containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight();
2538 }
2539
2540 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2541 {
2542     // If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned,
2543     // the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').
2544     LayoutUnit minLogicalHeight;
2545     if (!logicalHeightComputesAsNone(MinSize))
2546         minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2547     LayoutUnit maxLogicalHeight = logicalHeight;
2548     if (!logicalHeightComputesAsNone(MaxSize))
2549         maxLogicalHeight =  computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2550     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2551 }
2552
2553 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(const Length& logicalHeight) const
2554 {
2555     switch (logicalHeight.type()) {
2556         case Fixed:
2557             return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2558         case Percent:
2559         case Calculated:
2560         {
2561             RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
2562             while (cb->isAnonymous())
2563                 cb = cb->containingBlock();
2564             if (cb->isRenderBlock())
2565                 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2566
2567             // FIXME: This calculation is not patched for block-flow yet.
2568             // https://bugs.webkit.org/show_bug.cgi?id=46500
2569             if (cb->isOutOfFlowPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2570                 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2571                 RenderBlock* block = toRenderBlock(cb);
2572                 LogicalExtentComputedValues computedValues;
2573                 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2574                 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2575                 LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2576                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2577             }
2578
2579             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2580             // containing block's block-flow.
2581             // https://bugs.webkit.org/show_bug.cgi?id=46496
2582             LayoutUnit availableHeight;
2583             if (isOutOfFlowPositioned())
2584                 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2585             else {
2586                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
2587                 // It is necessary to use the border-box to match WinIE's broken
2588                 // box model.  This is essential for sizing inside
2589                 // table cells using percentage heights.
2590                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
2591                 // https://bugs.webkit.org/show_bug.cgi?id=46997
2592                 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2593                     if (cb->isTableCell()) {
2594                         // Don't let table cells squeeze percent-height replaced elements
2595                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2596                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
2597                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2598                     }
2599                     toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2600                     cb = cb->containingBlock();
2601                 }
2602             }
2603             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
2604         }
2605         case MinContent:
2606         case MaxContent:
2607         case FitContent:
2608         case FillAvailable:
2609             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingHeight()));
2610         default:
2611             return intrinsicLogicalHeight();
2612     }
2613 }
2614
2615 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
2616 {
2617     // http://www.w3.org/TR/CSS2/visudet.html#propdef-height - We are interested in the content height.
2618     return constrainContentBoxLogicalHeightByMinMax(availableLogicalHeightUsing(style()->logicalHeight(), heightType), -1);
2619 }
2620
2621 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
2622 {
2623     if (isRenderView())
2624         return isHorizontalWritingMode() ? toRenderView(this)->frameView()->unscaledVisibleContentSize().height() : toRenderView(this)->frameView()->unscaledVisibleContentSize().width();
2625
2626     // We need to stop here, since we don't want to increase the height of the table
2627     // artificially.  We're going to rely on this cell getting expanded to some new
2628     // height, and then when we lay out again we'll use the calculation below.
2629     if (isTableCell() && (h.isAuto() || h.isPercent())) {
2630         if (hasOverrideHeight())
2631             return overrideLogicalContentHeight();
2632         return logicalHeight() - borderAndPaddingLogicalHeight();
2633     }
2634
2635     if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
2636         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2637         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2638         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
2639     }
2640
2641     LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h, -1);
2642     if (heightIncludingScrollbar != -1)
2643         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2644
2645     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
2646     // https://bugs.webkit.org/show_bug.cgi?id=46500
2647     if (isRenderBlock() && isOutOfFlowPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2648         RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2649         LogicalExtentComputedValues computedValues;
2650         block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2651         LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2652         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2653     }
2654
2655     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2656     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
2657     if (heightType == ExcludeMarginBorderPadding) {
2658         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
2659         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
2660     }
2661     return availableHeight;
2662 }
2663
2664 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
2665 {
2666     LayoutUnit marginBefore;
2667     LayoutUnit marginAfter;
2668     computeMarginsForDirection(BlockDirection, containingBlock, containingBlockLogicalWidthForContent(), logicalHeight(), marginBefore, marginAfter,
2669         style()->marginBeforeUsing(containingBlock->style()),
2670         style()->marginAfterUsing(containingBlock->style()));
2671     // Note that in this 'positioning phase' of the layout we are using the containing block's writing mode rather than our own when calculating margins.
2672     // See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
2673     containingBlock->setMarginBeforeForChild(this, marginBefore);
2674     containingBlock->setMarginAfterForChild(this, marginAfter);
2675 }
2676
2677 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2678 {
2679     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2680         return containingBlockLogicalHeightForPositioned(containingBlock, false);
2681
2682     // Use viewport as container for top-level fixed-position elements.
2683     if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
2684         const RenderView* view = toRenderView(containingBlock);
2685         if (FrameView* frameView = view->frameView()) {
2686             LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2687             return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height();
2688         }
2689     }
2690
2691     if (containingBlock->isBox())
2692         return toRenderBox(containingBlock)->clientLogicalWidth();
2693
2694     ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2695
2696     const RenderInline* flow = toRenderInline(containingBlock);
2697     InlineFlowBox* first = flow->firstLineBox();
2698     InlineFlowBox* last = flow->lastLineBox();
2699
2700     // If the containing block is empty, return a width of 0.
2701     if (!first || !last)
2702         return 0;
2703
2704     LayoutUnit fromLeft;
2705     LayoutUnit fromRight;
2706     if (containingBlock->style()->isLeftToRightDirection()) {
2707         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2708         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2709     } else {
2710         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2711         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2712     }
2713
2714     return std::max<LayoutUnit>(0, fromRight - fromLeft);
2715 }
2716
2717 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2718 {
2719     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2720         return containingBlockLogicalWidthForPositioned(containingBlock, false);
2721
2722     // Use viewport as container for top-level fixed-position elements.
2723     if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
2724         const RenderView* view = toRenderView(containingBlock);
2725         if (FrameView* frameView = view->frameView()) {
2726             LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2727             return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
2728         }
2729     }
2730
2731     if (containingBlock->isBox()) {
2732         const RenderBlock* cb = containingBlock->isRenderBlock() ?
2733             toRenderBlock(containingBlock) : containingBlock->containingBlock();
2734         return cb->clientLogicalHeight();
2735     }
2736
2737     ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2738
2739     const RenderInline* flow = toRenderInline(containingBlock);
2740     InlineFlowBox* first = flow->firstLineBox();
2741     InlineFlowBox* last = flow->lastLineBox();
2742
2743     // If the containing block is empty, return a height of 0.
2744     if (!first || !last)
2745         return 0;
2746
2747     LayoutUnit heightResult;
2748     LayoutRect boundingBox = flow->linesBoundingBox();
2749     if (containingBlock->isHorizontalWritingMode())
2750         heightResult = boundingBox.height();
2751     else
2752         heightResult = boundingBox.width();
2753     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2754     return heightResult;
2755 }
2756
2757 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2758 {
2759     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2760         return;
2761
2762     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2763     if (child->parent()->style()->direction() == LTR) {
2764         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2765         for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2766             if (curr->isBox()) {
2767                 staticPosition += toRenderBox(curr)->logicalLeft();
2768                 if (toRenderBox(curr)->isRelPositioned())
2769                     staticPosition += toRenderBox(curr)->relativePositionOffset().width();
2770             } else if (curr->isInline()) {
2771                 if (curr->isRelPositioned()) {
2772                     if (!curr->style()->logicalLeft().isAuto())
2773                         staticPosition += curr->style()->logicalLeft().value();
2774                     else
2775                         staticPosition -= curr->style()->logicalRight().value();
2776                 }
2777             }
2778         }
2779         logicalLeft.setValue(Fixed, staticPosition);
2780     } else {
2781         RenderBox* enclosingBox = child->parent()->enclosingBox();
2782         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2783         for (RenderObject* curr = child->parent(); curr; curr = curr->container()) {
2784             if (curr->isBox()) {
2785                 if (curr != containerBlock) {
2786                     staticPosition -= toRenderBox(curr)->logicalLeft();
2787                     if (toRenderBox(curr)->isRelPositioned())
2788                         staticPosition -= toRenderBox(curr)->relativePositionOffset().width();
2789                 }
2790                 if (curr == enclosingBox)
2791                     staticPosition -= enclosingBox->logicalWidth();
2792             } else if (curr->isInline()) {
2793                 if (curr->isRelPositioned()) {
2794                     if (!curr->style()->logicalLeft().isAuto())
2795                         staticPosition -= curr->style()->logicalLeft().value();
2796                     else
2797                         staticPosition += curr->style()->logicalRight().value();
2798                 }
2799             }
2800             if (curr == containerBlock)
2801                 break;
2802         }
2803         logicalRight.setValue(Fixed, staticPosition);
2804     }
2805 }
2806
2807 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues) const
2808 {
2809     if (isReplaced()) {
2810         computePositionedLogicalWidthReplaced(computedValues);
2811         return;
2812     }
2813
2814     // QUESTIONS
2815     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2816     // the type 'static' in determining whether to calculate the static distance?
2817     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2818
2819     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2820     // than or less than the computed width().  Be careful of box-sizing and
2821     // percentage issues.
2822
2823     // The following is based off of the W3C Working Draft from April 11, 2006 of
2824     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2825     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2826     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2827     // correspond to text from the spec)
2828
2829
2830     // We don't use containingBlock(), since we may be positioned by an enclosing
2831     // relative positioned inline.
2832     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2833
2834     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2835
2836     // Use the container block's direction except when calculating the static distance
2837     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2838     // of the CSS 2.1 test suite
2839     TextDirection containerDirection = containerBlock->style()->direction();
2840
2841     bool isHorizontal = isHorizontalWritingMode();
2842     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2843     const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2844     const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2845
2846     Length logicalLeftLength = style()->logicalLeft();
2847     Length logicalRightLength = style()->logicalRight();
2848
2849     /*---------------------------------------------------------------------------*\
2850      * For the purposes of this section and the next, the term "static position"
2851      * (of an element) refers, roughly, to the position an element would have had
2852      * in the normal flow. More precisely:
2853      *
2854      * * The static position for 'left' is the distance from the left edge of the
2855      *   containing block to the left margin edge of a hypothetical box that would
2856      *   have been the first box of the element if its 'position' property had
2857      *   been 'static' and 'float' had been 'none'. The value is negative if the
2858      *   hypothetical box is to the left of the containing block.
2859      * * The static position for 'right' is the distance from the right edge of the
2860      *   containing block to the right margin edge of the same hypothetical box as
2861      *   above. The value is positive if the hypothetical box is to the left of the
2862      *   containing block's edge.
2863      *
2864      * But rather than actually calculating the dimensions of that hypothetical box,
2865      * user agents are free to make a guess at its probable position.
2866      *
2867      * For the purposes of calculating the static position, the containing block of
2868      * fixed positioned elements is the initial containing block instead of the
2869      * viewport, and all scrollable boxes should be assumed to be scrolled to their
2870      * origin.
2871     \*---------------------------------------------------------------------------*/
2872
2873     // see FIXME 1
2874     // Calculate the static distance if needed.
2875     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth);
2876
2877     // Calculate constraint equation values for 'width' case.
2878     computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2879                                        containerLogicalWidth, bordersPlusPadding,
2880                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2881                                        computedValues);
2882
2883     // Calculate constraint equation values for 'max-width' case.
2884     if (!style()->logicalMaxWidth().isMaxSizeNone()) {
2885         LogicalExtentComputedValues maxValues;
2886
2887         computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2888                                            containerLogicalWidth, bordersPlusPadding,
2889                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2890                                            maxValues);
2891
2892         if (computedValues.m_extent > maxValues.m_extent) {
2893             computedValues.m_extent = maxValues.m_extent;
2894             computedValues.m_position = maxValues.m_position;
2895             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
2896             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
2897         }
2898     }
2899
2900     // Calculate constraint equation values for 'min-width' case.
2901     if (!style()->logicalMinWidth().isZero() || style()->logicalMinWidth().isIntrinsic()) {
2902         LogicalExtentComputedValues minValues;
2903
2904         computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2905                                            containerLogicalWidth, bordersPlusPadding,
2906                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2907                                            minValues);
2908
2909         if (computedValues.m_extent < minValues.m_extent) {
2910             computedValues.m_extent = minValues.m_extent;
2911             computedValues.m_position = minValues.m_position;
2912             computedValues.m_margins.m_start = minValues.m_margins.m_start;
2913             computedValues.m_margins.m_end = minValues.m_margins.m_end;
2914         }
2915     }
2916
2917     computedValues.m_extent += bordersPlusPadding;
2918 }
2919
2920 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2921 {
2922     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2923     // along this axis, then we need to flip the coordinate.  This can only happen if the containing block is both a flipped mode and perpendicular to us.
2924     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2925         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2926         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2927     } else {
2928         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2929     }
2930 }
2931
2932 void RenderBox::shrinkToFitWidth(const LayoutUnit availableSpace, const LayoutUnit logicalLeftValue, const LayoutUnit bordersPlusPadding, LogicalExtentComputedValues& computedValues) const
2933 {
2934     // FIXME: would it be better to have shrink-to-fit in one step?
2935     LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2936     LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2937     LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2938     computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
2939 }
2940
2941 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2942                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2943                                                    const Length& logicalLeft, const Length& logicalRight, const Length& marginLogicalLeft,
2944                                                    const Length& marginLogicalRight, LogicalExtentComputedValues& computedValues) const
2945 {
2946     if (logicalWidth.isIntrinsic())
2947         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
2948
2949     // 'left' and 'right' cannot both be 'auto' because one would of been
2950     // converted to the static position already
2951     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2952
2953     LayoutUnit logicalLeftValue = 0;
2954
2955     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
2956
2957     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2958     bool logicalLeftIsAuto = logicalLeft.isAuto();
2959     bool logicalRightIsAuto = logicalRight.isAuto();
2960     LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
2961     LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
2962     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2963         /*-----------------------------------------------------------------------*\
2964          * If none of the three is 'auto': If both 'margin-left' and 'margin-
2965          * right' are 'auto', solve the equation under the extra constraint that
2966          * the two margins get equal values, unless this would make them negative,
2967          * in which case when direction of the containing block is 'ltr' ('rtl'),
2968          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2969          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2970          * solve the equation for that value. If the values are over-constrained,
2971          * ignore the value for 'left' (in case the 'direction' property of the
2972          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2973          * and solve for that value.
2974         \*-----------------------------------------------------------------------*/
2975         // NOTE:  It is not necessary to solve for 'right' in the over constrained
2976         // case because the value is not used for any further calculations.
2977
2978         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
2979         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
2980
2981         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
2982
2983         // Margins are now the only unknown
2984         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2985             // Both margins auto, solve for equality
2986             if (availableSpace >= 0) {
2987                 marginLogicalLeftValue = availableSpace / 2; // split the difference
2988                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2989             } else {
2990                 // Use the containing block's direction rather than the parent block's
2991                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2992                 if (containerDirection == LTR) {
2993                     marginLogicalLeftValue = 0;
2994                     marginLogicalRightValue = availableSpace; // will be negative
2995                 } else {
2996                     marginLogicalLeftValue = availableSpace; // will be negative
2997                     marginLogicalRightValue = 0;
2998                 }
2999             }
3000         } else if (marginLogicalLeft.isAuto()) {
3001             // Solve for left margin
3002             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3003             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3004         } else if (marginLogicalRight.isAuto()) {
3005             // Solve for right margin
3006             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3007             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3008         } else {
3009             // Over-constrained, solve for left if direction is RTL
3010             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3011             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3012
3013             // Use the containing block's direction rather than the parent block's
3014             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3015             if (containerDirection == RTL)
3016                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3017         }
3018     } else {
3019         /*--------------------------------------------------------------------*\
3020          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3021          * to 0, and pick the one of the following six rules that applies.
3022          *
3023          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3024          *    width is shrink-to-fit. Then solve for 'left'
3025          *
3026          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3027          * ------------------------------------------------------------------
3028          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3029          *    the 'direction' property of the containing block is 'ltr' set
3030          *    'left' to the static position, otherwise set 'right' to the
3031          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3032          *    or 'right' (if 'direction' is 'ltr').
3033          * ------------------------------------------------------------------
3034          *
3035          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3036          *    width is shrink-to-fit . Then solve for 'right'
3037          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3038          *    for 'left'
3039          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3040          *    for 'width'
3041          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3042          *    for 'right'
3043          *
3044          * Calculation of the shrink-to-fit width is similar to calculating the
3045          * width of a table cell using the automatic table layout algorithm.
3046          * Roughly: calculate the preferred width by formatting the content
3047          * without breaking lines other than where explicit line breaks occur,
3048          * and also calculate the preferred minimum width, e.g., by trying all
3049          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3050          * Thirdly, calculate the available width: this is found by solving
3051          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3052          * to 0.
3053          *
3054          * Then the shrink-to-fit width is:
3055          * min(max(preferred minimum width, available width), preferred width).
3056         \*--------------------------------------------------------------------*/
3057         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3058         // because the value is not used for any further calculations.
3059
3060         // Calculate margins, 'auto' margins are ignored.
3061         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3062         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3063
3064         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3065
3066         // FIXME: Is there a faster way to find the correct case?
3067         // Use rule/case that applies.
3068         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3069             // RULE 1: (use shrink-to-fit for width, and solve of left)
3070             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3071
3072             // FIXME: would it be better to have shrink-to-fit in one step?
3073             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3074             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3075             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3076             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3077             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3078         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3079             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3080             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3081
3082             shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
3083         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3084             // RULE 4: (solve for left)
3085             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3086             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3087         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3088             // RULE 5: (solve for width)
3089             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3090             if (autoWidthShouldFitContent())
3091                 shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
3092             else
3093                 computedValues.m_extent = std::max<LayoutUnit>(0, availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth)));
3094         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3095             // RULE 6: (no need solve for right)
3096             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3097             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3098         }
3099     }
3100
3101     // Use computed values to calculate the horizontal position.
3102
3103     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3104     // positioned, inline because right now, it is using the logical left position
3105     // of the first line box when really it should use the last line box.  When
3106     // this is fixed elsewhere, this block should be removed.
3107     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3108         const RenderInline* flow = toRenderInline(containerBlock);
3109         InlineFlowBox* firstLine = flow->firstLineBox();
3110         InlineFlowBox* lastLine = flow->lastLineBox();
3111         if (firstLine && lastLine && firstLine != lastLine) {
3112             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3113             return;
3114         }
3115     }
3116
3117     if (containerBlock->isBox() && toRenderBox(containerBlock)->scrollsOverflowY() && containerBlock->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
3118         logicalLeftValue = logicalLeftValue + toRenderBox(containerBlock)->verticalScrollbarWidth();
3119     }
3120
3121     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3122     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3123 }
3124
3125 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3126 {
3127     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3128         return;
3129
3130     // FIXME: The static distance computation has not been patched for mixed writing modes.
3131     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3132     for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3133         if (curr->isBox() && !curr->isTableRow())
3134             staticLogicalTop += toRenderBox(curr)->logicalTop();
3135     }
3136     logicalTop.setValue(Fixed, staticLogicalTop);
3137 }
3138
3139 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3140 {
3141     if (isReplaced()) {
3142         computePositionedLogicalHeightReplaced(computedValues);
3143         return;
3144     }
3145
3146     // The following is based off of the W3C Working Draft from April 11, 2006 of
3147     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3148     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3149     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3150     // correspond to text from the spec)
3151
3152
3153     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3154     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3155
3156     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3157
3158     RenderStyle* styleToUse = style();
3159     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3160     const Length marginBefore = styleToUse->marginBefore();
3161     const Length marginAfter = styleToUse->marginAfter();
3162     Length logicalTopLength = styleToUse->logicalTop();
3163     Length logicalBottomLength = styleToUse->logicalBottom();
3164
3165     /*---------------------------------------------------------------------------*\
3166      * For the purposes of this section and the next, the term "static position"
3167      * (of an element) refers, roughly, to the position an element would have had
3168      * in the normal flow. More precisely, the static position for 'top' is the
3169      * distance from the top edge of the containing block to the top margin edge
3170      * of a hypothetical box that would have been the first box of the element if
3171      * its 'position' property had been 'static' and 'float' had been 'none'. The
3172      * value is negative if the hypothetical box is above the containing block.
3173      *
3174      * But rather than actually calculating the dimensions of that hypothetical
3175      * box, user agents are free to make a guess at its probable position.
3176      *
3177      * For the purposes of calculating the static position, the containing block
3178      * of fixed positioned elements is the initial containing block instead of
3179      * the viewport.
3180     \*---------------------------------------------------------------------------*/
3181
3182     // see FIXME 1
3183     // Calculate the static distance if needed.
3184     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3185
3186     // Calculate constraint equation values for 'height' case.
3187     LayoutUnit logicalHeight = computedValues.m_extent;
3188     computePositionedLogicalHeightUsing(styleToUse->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3189                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3190                                         computedValues);
3191
3192     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3193     // see FIXME 2
3194
3195     // Calculate constraint equation values for 'max-height' case.
3196     if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
3197         LogicalExtentComputedValues maxValues;
3198
3199         computePositionedLogicalHeightUsing(styleToUse->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3200                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3201                                             maxValues);
3202
3203         if (computedValues.m_extent > maxValues.m_extent) {
3204             computedValues.m_extent = maxValues.m_extent;
3205             computedValues.m_position = maxValues.m_position;
3206             computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3207             computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3208         }
3209     }
3210
3211     // Calculate constraint equation values for 'min-height' case.
3212     if (!styleToUse->logicalMinHeight().isZero() || styleToUse->logicalMinHeight().isIntrinsic()) {
3213         LogicalExtentComputedValues minValues;
3214
3215         computePositionedLogicalHeightUsing(styleToUse->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3216                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3217                                             minValues);
3218
3219         if (computedValues.m_extent < minValues.m_extent) {
3220             computedValues.m_extent = minValues.m_extent;
3221             computedValues.m_position = minValues.m_position;
3222             computedValues.m_margins.m_before = minValues.m_margins.m_before;
3223             computedValues.m_margins.m_after = minValues.m_margins.m_after;
3224         }
3225     }
3226
3227     // Set final height value.
3228     computedValues.m_extent += bordersPlusPadding;
3229 }
3230
3231 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3232 {
3233     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3234     // along this axis, then we need to flip the coordinate.  This can only happen if the containing block is both a flipped mode and perpendicular to us.
3235     if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3236         || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3237         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3238
3239     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3240     if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3241         if (child->isHorizontalWritingMode())
3242             logicalTopPos += containerBlock->borderBottom();
3243         else
3244             logicalTopPos += containerBlock->borderRight();
3245     } else {
3246         if (child->isHorizontalWritingMode())
3247             logicalTopPos += containerBlock->borderTop();
3248         else
3249             logicalTopPos += containerBlock->borderLeft();
3250     }
3251 }
3252
3253 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3254                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3255                                                     const Length& logicalTop, const Length& logicalBottom, const Length& marginBefore,
3256                                                     const Length& marginAfter, LogicalExtentComputedValues& computedValues) const
3257 {
3258     // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3259     // converted to the static position in computePositionedLogicalHeight()
3260     ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3261
3262     LayoutUnit logicalHeightValue;
3263     LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
3264
3265     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3266
3267     LayoutUnit logicalTopValue = 0;
3268
3269     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3270     bool logicalTopIsAuto = logicalTop.isAuto();
3271     bool logicalBottomIsAuto = logicalBottom.isAuto();
3272
3273     LayoutUnit resolvedLogicalHeight;
3274     // Height is never unsolved for tables.
3275     if (isTable()) {
3276         resolvedLogicalHeight = contentLogicalHeight;
3277         logicalHeightIsAuto = false;
3278     } else {
3279         if (logicalHeightLength.isIntrinsic())
3280             resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
3281         else
3282             resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
3283     }
3284
3285     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3286         /*-----------------------------------------------------------------------*\
3287          * If none of the three are 'auto': If both 'margin-top' and 'margin-
3288          * bottom' are 'auto', solve the equation under the extra constraint that
3289          * the two margins get equal values. If one of 'margin-top' or 'margin-
3290          * bottom' is 'auto', solve the equation for that value. If the values
3291          * are over-constrained, ignore the value for 'bottom' and solve for that
3292          * value.
3293         \*-----------------------------------------------------------------------*/
3294         // NOTE:  It is not necessary to solve for 'bottom' in the over constrained
3295         // case because the value is not used for any further calculations.
3296
3297         logicalHeightValue = resolvedLogicalHeight;
3298         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3299
3300         const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
3301
3302         // Margins are now the only unknown
3303         if (marginBefore.isAuto() && marginAfter.isAuto()) {
3304             // Both margins auto, solve for equality
3305             // NOTE: This may result in negative values.
3306             computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3307             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3308         } else if (marginBefore.isAuto()) {
3309             // Solve for top margin
3310             computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3311             computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3312         } else if (marginAfter.isAuto()) {
3313             // Solve for bottom margin
3314             computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3315             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3316         } else {
3317             // Over-constrained, (no need solve for bottom)
3318             computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3319             computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3320         }
3321     } else {
3322         /*--------------------------------------------------------------------*\
3323          * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3324          * to 0, and pick the one of the following six rules that applies.
3325          *
3326          * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3327          *    the height is based on the content, and solve for 'top'.
3328          *
3329          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3330          * ------------------------------------------------------------------
3331          * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3332          *    set 'top' to the static position, and solve for 'bottom'.
3333          * ------------------------------------------------------------------
3334          *
3335          * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3336          *    the height is based on the content, and solve for 'bottom'.
3337          * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3338          *    solve for 'top'.
3339          * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3340          *    solve for 'height'.
3341          * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3342          *    solve for 'bottom'.
3343         \*--------------------------------------------------------------------*/
3344         // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3345         // because the value is not used for any further calculations.
3346
3347         // Calculate margins, 'auto' margins are ignored.
3348         computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
3349         computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);
3350
3351         const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
3352
3353         // Use rule/case that applies.
3354         if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3355             // RULE 1: (height is content based, solve of top)
3356             logicalHeightValue = contentLogicalHeight;
3357             logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
3358         } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3359             // RULE 3: (height is content based, no need solve of bottom)
3360             logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3361             logicalHeightValue = contentLogicalHeight;
3362         } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3363             // RULE 4: (solve of top)
3364             logicalHeightValue = resolvedLogicalHeight;
3365             logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
3366         } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3367             // RULE 5: (solve of height)
3368             logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3369             logicalHeightValue = std::max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight)));
3370         } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3371             // RULE 6: (no need solve of bottom)
3372             logicalHeightValue = resolvedLogicalHeight;
3373             logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3374         }
3375     }
3376     computedValues.m_extent = logicalHeightValue;
3377
3378     // Use computed values to calculate the vertical position.
3379     computedValues.m_position = logicalTopValue + computedValues.m_margins.m_before;
3380     computeLogicalTopPositionedOffset(computedValues.m_position, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3381 }
3382
3383 void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValues& computedValues) const
3384 {
3385     // The following is based off of the W3C Working Draft from April 11, 2006 of
3386     // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3387     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3388     // (block-style-comments in this function correspond to text from the spec and
3389     // the numbers correspond to numbers in spec)
3390
3391     // We don't use containingBlock(), since we may be positioned by an enclosing
3392     // relative positioned inline.
3393     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3394
3395     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3396     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3397
3398     // To match WinIE, in quirks mode use the parent's 'direction' property
3399     // instead of the the container block's.
3400     TextDirection containerDirection = containerBlock->style()->direction();
3401
3402     // Variables to solve.
3403     bool isHorizontal = isHorizontalWritingMode();
3404     Length logicalLeft = style()->logicalLeft();
3405     Length logicalRight = style()->logicalRight();
3406     Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3407     Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3408     LayoutUnit& marginLogicalLeftAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3409     LayoutUnit& marginLogicalRightAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3410
3411     /*-----------------------------------------------------------------------*\
3412      * 1. The used value of 'width' is determined as for inline replaced
3413      *    elements.
3414     \*-----------------------------------------------------------------------*/
3415     // NOTE: This value of width is FINAL in that the min/max width calculations
3416     // are dealt with in computeReplacedWidth().  This means that the steps to produce
3417     // correct max/min in the non-replaced version, are not necessary.
3418     computedValues.m_extent = computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth();
3419
3420     const LayoutUnit availableSpace = containerLogicalWidth - computedValues.m_extent;
3421
3422     /*-----------------------------------------------------------------------*\
3423      * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3424      *    of the containing block is 'ltr', set 'left' to the static position;
3425      *    else if 'direction' is 'rtl', set 'right' to the static position.
3426     \*-----------------------------------------------------------------------*/
3427     // see FIXME 1
3428     computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth);
3429
3430     /*-----------------------------------------------------------------------*\
3431      * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3432      *    or 'margin-right' with '0'.
3433     \*-----------------------------------------------------------------------*/
3434     if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3435         if (marginLogicalLeft.isAuto())
3436             marginLogicalLeft.setValue(Fixed, 0);
3437         if (marginLogicalRight.isAuto())
3438             marginLogicalRight.setValue(Fixed, 0);
3439     }
3440
3441     /*-----------------------------------------------------------------------*\
3442      * 4. If at this point both 'margin-left' and 'margin-right' are still
3443      *    'auto', solve the equation under the extra constraint that the two
3444      *    margins must get equal values, unless this would make them negative,
3445      *    in which case when the direction of the containing block is 'ltr'
3446      *    ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3447      *    'margin-right' ('margin-left').
3448     \*-----------------------------------------------------------------------*/
3449     LayoutUnit logicalLeftValue = 0;
3450     LayoutUnit logicalRightValue = 0;
3451
3452     if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3453         // 'left' and 'right' cannot be 'auto' due to step 3
3454         ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3455
3456         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3457         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3458
3459         LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3460         if (difference > 0) {
3461             marginLogicalLeftAlias = difference / 2; // split the difference
3462             marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3463         } else {
3464             // Use the containing block's direction rather than the parent block's
3465             // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3466             if (containerDirection == LTR) {
3467                 marginLogicalLeftAlias = 0;
3468                 marginLogicalRightAlias = difference; // will be negative
3469             } else {
3470                 marginLogicalLeftAlias = difference; // will be negative
3471                 marginLogicalRightAlias = 0;
3472             }
3473         }
3474
3475     /*-----------------------------------------------------------------------*\
3476      * 5. If at this point there is an 'auto' left, solve the equation for
3477      *    that value.
3478     \*-----------------------------------------------------------------------*/
3479     } else if (logicalLeft.isAuto()) {
3480         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3481         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3482         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3483
3484         // Solve for 'left'
3485         logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3486     } else if (logicalRight.isAuto()) {
3487         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3488         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3489         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3490
3491         // Solve for 'right'
3492         logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3493     } else if (marginLogicalLeft.isAuto()) {
3494         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3495         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3496         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3497
3498         // Solve for 'margin-left'
3499         marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3500     } else if (marginLogicalRight.isAuto()) {
3501         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3502         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3503         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3504
3505         // Solve for 'margin-right'
3506         marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3507     } else {
3508         // Nothing is 'auto', just calculate the values.
3509         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3510         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3511         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3512         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3513         // If the containing block is right-to-left, then push the left position as far to the right as possible
3514         if (containerDirection == RTL) {
3515             int totalLogicalWidth = computedValues.m_extent + logicalLeftValue + logicalRightValue +  marginLogicalLeftAlias + marginLogicalRightAlias;
3516             logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3517         }
3518     }
3519
3520     /*-----------------------------------------------------------------------*\
3521      * 6. If at this point the values are over-constrained, ignore the value
3522      *    for either 'left' (in case the 'direction' property of the
3523      *    containing block is 'rtl') or 'right' (in case 'direction' is
3524      *    'ltr') and solve for that value.
3525     \*-----------------------------------------------------------------------*/
3526     // NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
3527
3528     // FIXME: Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space, so that
3529     // can make the result here rather complicated to compute.
3530
3531     // Use computed values to calculate the horizontal position.
3532
3533     // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3534     // positioned, inline containing block because right now, it is using the logical left position
3535     // of the first line box when really it should use the last line box.  When
3536     // this is fixed elsewhere, this block should be removed.
3537     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3538         const RenderInline* flow = toRenderInline(containerBlock);
3539         InlineFlowBox* firstLine = flow->firstLineBox();
3540         InlineFlowBox* lastLine = flow->lastLineBox();
3541         if (firstLine && lastLine && firstLine != lastLine) {
3542             computedValues.m_position = logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3543             return;
3544         }
3545     }
3546
3547     LayoutUnit logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
3548     computeLogicalLeftPositionedOffset(logicalLeftPos, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3549     computedValues.m_position = logicalLeftPos;
3550 }
3551
3552 void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValues& computedValues) const
3553 {
3554     // The following is based off of the W3C Working Draft from April 11, 2006 of
3555     // CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
3556     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
3557     // (block-style-comments in this function correspond to text from the spec and
3558     // the numbers correspond to numbers in spec)
3559
3560     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3561     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3562
3563     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3564     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3565
3566     // Variables to solve.
3567     Length marginBefore = style()->marginBefore();
3568     Length marginAfter = style()->marginAfter();
3569     LayoutUnit& marginBeforeAlias = computedValues.m_margins.m_before;
3570     LayoutUnit& marginAfterAlias = computedValues.m_margins.m_after;
3571
3572     Length logicalTop = style()->logicalTop();
3573     Length logicalBottom = style()->logicalBottom();
3574
3575     /*-----------------------------------------------------------------------*\
3576      * 1. The used value of 'height' is determined as for inline replaced
3577      *    elements.
3578     \*-----------------------------------------------------------------------*/
3579     // NOTE: This value of height is FINAL in that the min/max height calculations
3580     // are dealt with in computeReplacedHeight().  This means that the steps to produce
3581     // correct max/min in the non-replaced version, are not necessary.
3582     computedValues.m_extent = computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight();
3583     const LayoutUnit availableSpace = containerLogicalHeight - computedValues.m_extent;
3584
3585     /*-----------------------------------------------------------------------*\
3586      * 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
3587      *    with the element's static position.
3588     \*-----------------------------------------------------------------------*/
3589     // see FIXME 1
3590     computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
3591
3592     /*-----------------------------------------------------------------------*\
3593      * 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
3594      *    'margin-bottom' with '0'.
3595     \*-----------------------------------------------------------------------*/
3596     // FIXME: The spec. says that this step should only be taken when bottom is
3597     // auto, but if only top is auto, this makes step 4 impossible.
3598     if (logicalTop.isAuto() || logicalBottom.isAuto()) {
3599         if (marginBefore.isAuto())
3600             marginBefore.setValue(Fixed, 0);
3601         if (marginAfter.isAuto())
3602             marginAfter.setValue(Fixed, 0);
3603     }
3604
3605     /*-----------------------------------------------------------------------*\
3606      * 4. If at this point both 'margin-top' and 'margin-bottom' are still
3607      *    'auto', solve the equation under the extra constraint that the two
3608      *    margins must get equal values.
3609     \*-----------------------------------------------------------------------*/
3610     LayoutUnit logicalTopValue = 0;
3611     LayoutUnit logicalBottomValue = 0;
3612
3613     if (marginBefore.isAuto() && marginAfter.isAuto()) {
3614         // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
3615         ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
3616
3617         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3618         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3619
3620         LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
3621         // NOTE: This may result in negative values.
3622         marginBeforeAlias =  difference / 2; // split the difference
3623         marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
3624
3625     /*-----------------------------------------------------------------------*\
3626      * 5. If at this point there is only one 'auto' left, solve the equation
3627      *    for that value.
3628     \*-----------------------------------------------------------------------*/
3629     } else if (logicalTop.isAuto()) {
3630         marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3631         marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3632         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3633
3634         // Solve for 'top'
3635         logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
3636     } else if (logicalBottom.isAuto()) {
3637         marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3638         marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3639         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3640
3641         // Solve for 'bottom'
3642         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3643         // use the value.
3644     } else if (marginBefore.isAuto()) {
3645         marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3646         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3647         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3648
3649         // Solve for 'margin-top'
3650         marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
3651     } else if (marginAfter.isAuto()) {
3652         marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3653         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3654         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3655
3656         // Solve for 'margin-bottom'
3657         marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
3658     } else {
3659         // Nothing is 'auto', just calculate the values.
3660         marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3661         marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3662         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3663         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3664         // use the value.
3665      }
3666
3667     /*-----------------------------------------------------------------------*\
3668      * 6. If at this point the values are over-constrained, ignore the value
3669      *    for 'bottom' and solve for that value.
3670     \*-----------------------------------------------------------------------*/
3671     // NOTE: It is not necessary to do this step because we don't end up using
3672     // the value of 'bottom' regardless of whether the values are over-constrained
3673     // or not.
3674
3675     // Use computed values to calculate the vertical position.
3676     LayoutUnit logicalTopPos = logicalTopValue + marginBeforeAlias;
3677     computeLogicalTopPositionedOffset(logicalTopPos, this, computedValues.m_extent, containerBlock, containerLogicalHeight);
3678     computedValues.m_position = logicalTopPos;
3679 }
3680
3681 LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3682 {
3683     // VisiblePositions at offsets inside containers either a) refer to the positions before/after
3684     // those containers (tables and select elements) or b) refer to the position inside an empty block.
3685     // They never refer to children.
3686     // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
3687
3688     LayoutRect rect(location(), LayoutSize(caretWidth, height()));
3689     bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
3690
3691     if ((!caretOffset) ^ ltr)
3692         rect.move(LayoutSize(width() - caretWidth, 0));
3693
3694     if (box) {
3695         RootInlineBox& rootBox = box->root();
3696         LayoutUnit top = rootBox.lineTop();
3697         rect.setY(top);
3698         rect.setHeight(rootBox.lineBottom() - top);
3699     }
3700
3701     // If height of box is smaller than font height, use the latter one,
3702     // otherwise the caret might become invisible.
3703     //
3704     // Also, if the box is not a replaced element, always use the font height.
3705     // This prevents the "big caret" bug described in:
3706     // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
3707     //
3708     // FIXME: ignoring :first-line, missing good reason to take care of
3709     LayoutUnit fontHeight = style()->fontMetrics().height();
3710     if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
3711         rect.setHeight(fontHeight);
3712
3713     if (extraWidthToEndOfLine)
3714         *extraWidthToEndOfLine = x() + width() - rect.maxX();
3715
3716     // Move to local coords
3717     rect.moveBy(-location());
3718
3719     // FIXME: Border/padding should be added for all elements but this workaround
3720     // is needed because we use offsets inside an "atomic" element to represent
3721     // positions before and after the element in deprecated editing offsets.
3722     if (node() && !(editingIgnoresContent(node()) || isRenderedTableElement(node()))) {
3723         rect.setX(rect.x() + borderLeft() + paddingLeft());
3724         rect.setY(rect.y() + paddingTop() + borderTop());
3725     }
3726
3727     if (!isHorizontalWritingMode())
3728         return rect.transposedRect();
3729
3730     return rect;
3731 }
3732
3733 PositionWithAffinity RenderBox::positionForPoint(const LayoutPoint& point)
3734 {
3735     // no children...return this render object's element, if there is one, and offset 0
3736     RenderObject* firstChild = slowFirstChild();
3737     if (!firstChild)
3738         return createPositionWithAffinity(nonPseudoNode() ? firstPositionInOrBeforeNode(nonPseudoNode()) : Position());
3739
3740     if (isTable() && nonPseudoNode()) {
3741         LayoutUnit right = contentWidth() + borderAndPaddingWidth();
3742         LayoutUnit bottom = contentHeight() + borderAndPaddingHeight();
3743
3744         if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) {
3745             if (point.x() <= right / 2)
3746                 return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
3747             return createPositionWithAffinity(lastPositionInOrAfterNode(nonPseudoNode()));
3748         }
3749     }
3750
3751     // Pass off to the closest child.
3752     LayoutUnit minDist = LayoutUnit::max();
3753     RenderBox* closestRenderer = 0;
3754     LayoutPoint adjustedPoint = point;
3755     if (isTableRow())
3756         adjustedPoint.moveBy(location());
3757
3758     for (RenderObject* renderObject = firstChild; renderObject; renderObject = renderObject->nextSibling()) {
3759         if ((!renderObject->slowFirstChild() && !renderObject->isInline() && !renderObject->isRenderBlockFlow() )
3760             || renderObject->style()->visibility() != VISIBLE)
3761             continue;
3762
3763         if (!renderObject->isBox())
3764             continue;
3765
3766         RenderBox* renderer = toRenderBox(renderObject);
3767
3768         LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? LayoutUnit() : renderer->y());
3769         LayoutUnit bottom = top + renderer->contentHeight();
3770         LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? LayoutUnit() : renderer->x());
3771         LayoutUnit right = left + renderer->contentWidth();
3772
3773         if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) {
3774             if (renderer->isTableRow())
3775                 return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset());
3776             return renderer->positionForPoint(point - renderer->locationOffset());
3777         }
3778
3779         // Find the distance from (x, y) to the box.  Split the space around the box into 8 pieces
3780         // and use a different compare depending on which piece (x, y) is in.
3781         LayoutPoint cmp;
3782         if (point.x() > right) {
3783             if (point.y() < top)
3784                 cmp = LayoutPoint(right, top);
3785             else if (point.y() > bottom)
3786                 cmp = LayoutPoint(right, bottom);
3787             else
3788                 cmp = LayoutPoint(right, point.y());
3789         } else if (point.x() < left) {
3790             if (point.y() < top)
3791                 cmp = LayoutPoint(left, top);
3792             else if (point.y() > bottom)
3793                 cmp = LayoutPoint(left, bottom);
3794             else
3795                 cmp = LayoutPoint(left, point.y());
3796         } else {
3797             if (point.y() < top)
3798                 cmp = LayoutPoint(point.x(), top);
3799             else
3800                 cmp = LayoutPoint(point.x(), bottom);
3801         }
3802
3803         LayoutSize difference = cmp - point;
3804
3805         LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height();
3806         if (dist < minDist) {
3807             closestRenderer = renderer;
3808             minDist = dist;
3809         }
3810     }
3811
3812     if (closestRenderer)
3813         return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset());
3814     return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
3815 }
3816
3817 bool RenderBox::shrinkToAvoidFloats() const
3818 {
3819     // Floating objects don't shrink.  Objects that don't avoid floats don't shrink.  Marquees don't shrink.
3820     if ((isInline() && !isMarquee()) || !avoidsFloats() || isFloating())
3821         return false;
3822
3823     // Only auto width objects can possibly shrink to avoid floats.
3824     return style()->width().isAuto();
3825 }
3826
3827 static bool isReplacedElement(Node* node)
3828 {
3829     // Checkboxes and radioboxes are not isReplaced() nor do they have their own renderer in which to override avoidFloats().
3830     return node && node->isElementNode() && toElement(node)->isFormControlElement();
3831 }
3832
3833 bool RenderBox::avoidsFloats() const
3834 {
3835     return isReplaced() || isReplacedElement(node()) || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isFlexItemIncludingDeprecated();
3836 }
3837
3838 InvalidationReason RenderBox::getPaintInvalidationReason(const RenderLayerModelObject& paintInvalidationContainer,
3839     const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const LayoutRect& newBounds, const LayoutPoint& newLocation)
3840 {
3841     InvalidationReason invalidationReason = RenderBoxModelObject::getPaintInvalidationReason(paintInvalidationContainer, oldBounds, oldLocation, newBounds, newLocation);
3842     if (invalidationReason != InvalidationNone && invalidationReason != InvalidationIncremental)
3843         return invalidationReason;
3844
3845     if (!style()->hasBackground() && !style()->hasBoxDecorations())
3846         return invalidationReason;
3847
3848     LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
3849     LayoutSize newBorderBoxSize = size();
3850
3851     if (oldBorderBoxSize == newBorderBoxSize)
3852         return invalidationReason;
3853
3854     // FIXME: Implement correct incremental invalidation for visual overflowing effects.
3855     if (style()->hasVisualOverflowingEffect() || style()->hasAppearance() || style()->hasFilter())
3856         return InvalidationBorderBoxChange;
3857
3858     if (style()->hasBorderRadius()) {
3859         // If a border-radius exists and width/height is smaller than radius width/height,
3860         // we need to fully invalidate to cover the changed radius.
3861         RoundedRect oldRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), oldBorderBoxSize));
3862         RoundedRect newRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), newBorderBoxSize));
3863         if (oldRoundedRect.radii() != newRoundedRect.radii())
3864             return InvalidationBorderBoxChange;
3865     }
3866
3867     if (oldBorderBoxSize.width() != newBorderBoxSize.width() && mustInvalidateBackgroundOrBorderPaintOnWidthChange())
3868         return InvalidationBorderBoxChange;
3869     if (oldBorderBoxSize.height() != newBorderBoxSize.height() && mustInvalidateBackgroundOrBorderPaintOnHeightChange())
3870         return InvalidationBorderBoxChange;
3871
3872     return InvalidationIncremental;
3873 }
3874
3875 void RenderBox::incrementallyInvalidatePaint(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutRect& newBounds, const LayoutPoint& positionFromPaintInvalidationBacking)
3876 {
3877     RenderObject::incrementallyInvalidatePaint(paintInvalidationContainer, oldBounds, newBounds, positionFromPaintInvalidationBacking);
3878
3879     bool hasBoxDecorations = style()->hasBoxDecorations();
3880     if (!style()->hasBackground() && !hasBoxDecorations)
3881         return;
3882
3883     LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
3884     LayoutSize newBorderBoxSize = size();
3885
3886     // If border box size didn't change, RenderObject's incrementallyInvalidatePaint() is good.
3887     if (oldBorderBoxSize == newBorderBoxSize)
3888         return;
3889
3890     // If size of the paint invalidation rect equals to size of border box, RenderObject::incrementallyInvalidatePaint()
3891     // is good for boxes having background without box decorations.
3892     ASSERT(oldBounds.location() == newBounds.location()); // Otherwise we won't do incremental invalidation.
3893     if (!hasBoxDecorations
3894         && positionFromPaintInvalidationBacking == newBounds.location()
3895         && oldBorderBoxSize == oldBounds.size()
3896         && newBorderBoxSize == newBounds.size())
3897         return;
3898
3899     // Invalidate the right delta part and the right border of the old or new box which has smaller width.
3900     LayoutUnit deltaWidth = absoluteValue(oldBorderBoxSize.width() - newBorderBoxSize.width());
3901     if (deltaWidth) {
3902         LayoutUnit smallerWidth = std::min(oldBorderBoxSize.width(), newBorderBoxSize.width());
3903         LayoutUnit borderTopRightRadiusWidth = valueForLength(style()->borderTopRightRadius().width(), smallerWidth);
3904         LayoutUnit borderBottomRightRadiusWidth = valueForLength(style()->borderBottomRightRadius().width(), smallerWidth);
3905         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight(), std::max(borderTopRightRadiusWidth, borderBottomRightRadiusWidth));
3906         LayoutRect rightDeltaRect(positionFromPaintInvalidationBacking.x() + smallerWidth - borderWidth,
3907             positionFromPaintInvalidationBacking.y(),
3908             deltaWidth + borderWidth,
3909             std::max(oldBorderBoxSize.height(), newBorderBoxSize.height()));
3910         invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, rightDeltaRect, oldBounds, newBounds);
3911     }
3912
3913     // Invalidate the bottom delta part and the bottom border of the old or new box which has smaller height.
3914     LayoutUnit deltaHeight = absoluteValue(oldBorderBoxSize.height() - newBorderBoxSize.height());
3915     if (deltaHeight) {
3916         LayoutUnit smallerHeight = std::min(oldBorderBoxSize.height(), newBorderBoxSize.height());
3917         LayoutUnit borderBottomLeftRadiusHeight = valueForLength(style()->borderBottomLeftRadius().height(), smallerHeight);
3918         LayoutUnit borderBottomRightRadiusHeight = valueForLength(style()->borderBottomRightRadius().height(), smallerHeight);
3919         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom(), std::max(borderBottomLeftRadiusHeight, borderBottomRightRadiusHeight));
3920         LayoutRect bottomDeltaRect(positionFromPaintInvalidationBacking.x(),
3921             positionFromPaintInvalidationBacking.y() + smallerHeight - borderHeight,
3922             std::max(oldBorderBoxSize.width(), newBorderBoxSize.width()),
3923             deltaHeight + borderHeight);
3924         invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, bottomDeltaRect, oldBounds, newBounds);
3925     }
3926 }
3927
3928 void RenderBox::invalidatePaintRectClippedByOldAndNewBounds(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& rect, const LayoutRect& oldBounds, const LayoutRect& newBounds)
3929 {
3930     if (rect.isEmpty())
3931         return;
3932     LayoutRect rectClippedByOldBounds = intersection(rect, oldBounds);
3933     LayoutRect rectClippedByNewBounds = intersection(rect, newBounds);
3934     // Invalidate only once if the clipped rects equal.
3935     if (rectClippedByOldBounds == rectClippedByNewBounds) {
3936         invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, InvalidationIncremental);
3937         return;
3938     }
3939     // Invalidate the bigger one if one contains another. Otherwise invalidate both.
3940     if (!rectClippedByNewBounds.contains(rectClippedByOldBounds))
3941         invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, InvalidationIncremental);
3942     if (!rectClippedByOldBounds.contains(rectClippedByNewBounds))
3943         invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByNewBounds, InvalidationIncremental);
3944 }
3945
3946 void RenderBox::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
3947 {
3948     ASSERT(!needsLayout());
3949     // If fragmentation height has changed, we need to lay out. No need to enter the renderer if it
3950     // is childless, though.
3951     if (view()->layoutState()->pageLogicalHeightChanged() && slowFirstChild())
3952         layoutScope.setChildNeedsLayout(this);
3953 }
3954
3955 void RenderBox::addVisualEffectOverflow()
3956 {
3957     if (!style()->hasVisualOverflowingEffect())
3958         return;
3959
3960     // Add in the final overflow with shadows, outsets and outline combined.
3961     LayoutRect visualEffectOverflow = borderBoxRect();
3962     visualEffectOverflow.expand(computeVisualEffectOverflowExtent());
3963     addVisualOverflow(visualEffectOverflow);
3964 }
3965
3966 LayoutBoxExtent RenderBox::computeVisualEffectOverflowExtent() const
3967 {
3968     ASSERT(style()->hasVisualOverflowingEffect());
3969
3970     LayoutUnit top;
3971     LayoutUnit right;
3972     LayoutUnit bottom;
3973     LayoutUnit left;
3974
3975     if (style()->boxShadow()) {
3976         style()->getBoxShadowExtent(top, right, bottom, left);
3977
3978         // Box shadow extent's top and left are negative when extend to left and top direction, respectively.
3979         // Negate to make them positive.
3980         top = -top;
3981         left = -left;
3982     }
3983
3984     if (style()->hasBorderImageOutsets()) {
3985         LayoutBoxExtent borderOutsets = style()->borderImageOutsets();
3986         top = std::max(top, borderOutsets.top());
3987         right = std::max(right, borderOutsets.right());
3988         bottom = std::max(bottom, borderOutsets.bottom());
3989         left = std::max(left, borderOutsets.left());
3990     }
3991
3992     if (style()->hasOutline()) {
3993         if (style()->outlineStyleIsAuto()) {
3994             // The result focus ring rects are in coordinates of this object's border box.
3995             Vector<LayoutRect> focusRingRects;
3996             addFocusRingRects(focusRingRects, LayoutPoint(), this);
3997             LayoutRect rect = unionRect(focusRingRects);
3998
3999             int outlineSize = GraphicsContext::focusRingOutsetExtent(style()->outlineOffset(), style()->outlineWidth());
4000             top = std::max(top, -rect.y() + outlineSize);
4001             right = std::max(right, rect.maxX() - width() + outlineSize);
4002             bottom = std::max(bottom, rect.maxY() - height() + outlineSize);
4003             left = std::max(left, -rect.x() + outlineSize);
4004         } else {
4005             LayoutUnit outlineSize = style()->outlineSize();
4006             top = std::max(top, outlineSize);
4007             right = std::max(right, outlineSize);
4008             bottom = std::max(bottom, outlineSize);
4009             left = std::max(left, outlineSize);
4010         }
4011     }
4012
4013     return LayoutBoxExtent(top, right, bottom, left);
4014 }
4015
4016 void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
4017 {
4018     // Never allow flow threads to propagate overflow up to a parent.
4019     if (child->isRenderFlowThread())
4020         return;
4021
4022     // Only propagate layout overflow from the child if the child isn't clipping its overflow.  If it is, then
4023     // its overflow is internal to it, and we don't care about it.  layoutOverflowRectForPropagation takes care of this
4024     // and just propagates the border box rect instead.
4025     LayoutRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
4026     childLayoutOverflowRect.move(delta);
4027     addLayoutOverflow(childLayoutOverflowRect);
4028
4029     // Add in visual overflow from the child.  Even if the child clips its overflow, it may still
4030     // have visual overflow of its own set from box shadows or reflections.  It is unnecessary to propagate this
4031     // overflow if we are clipping our own overflow.
4032     if (child->hasSelfPaintingLayer())
4033         return;
4034     LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
4035     childVisualOverflowRect.move(delta);
4036     addContentsVisualOverflow(childVisualOverflowRect);
4037 }
4038
4039 void RenderBox::addLayoutOverflow(const LayoutRect& rect)
4040 {
4041     LayoutRect clientBox = noOverflowRect();
4042     if (clientBox.contains(rect) || rect.isEmpty())
4043         return;
4044
4045     // For overflow clip objects, we don't want to propagate overflow into unreachable areas.
4046     LayoutRect overflowRect(rect);
4047     if (hasOverflowClip() || isRenderView()) {
4048         // Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl
4049         // writing modes.  At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
4050         // and vertical-lr/rl as the same.
4051         bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
4052         bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
4053         if (isFlexibleBox() && style()->isReverseFlexDirection()) {
4054             RenderFlexibleBox* flexibleBox = toRenderFlexibleBox(this);
4055             if (flexibleBox->isHorizontalFlow())
4056                 hasLeftOverflow = true;
4057             else
4058                 hasTopOverflow = true;
4059         }
4060
4061         if (!hasTopOverflow)
4062             overflowRect.shiftYEdgeTo(std::max(overflowRect.y(), clientBox.y()));
4063         else
4064             overflowRect.shiftMaxYEdgeTo(std::min(overflowRect.maxY(), clientBox.maxY()));
4065         if (!hasLeftOverflow)
4066             overflowRect.shiftXEdgeTo(std::max(overflowRect.x(), clientBox.x()));
4067         else
4068             overflowRect.shiftMaxXEdgeTo(std::min(overflowRect.maxX(), clientBox.maxX()));
4069
4070         // Now re-test with the adjusted rectangle and see if it has become unreachable or fully
4071         // contained.
4072         if (clientBox.contains(overflowRect) || overflowRect.isEmpty())
4073             return;
4074     }
4075
4076     if (!m_overflow)
4077         m_overflow = adoptPtr(new RenderOverflow(clientBox, borderBoxRect()));
4078
4079     m_overflow->addLayoutOverflow(overflowRect);
4080 }
4081
4082 void RenderBox::addVisualOverflow(const LayoutRect& rect)
4083 {
4084     LayoutRect borderBox = borderBoxRect();
4085     if (borderBox.contains(rect) || rect.isEmpty())
4086         return;
4087
4088     if (!m_overflow)
4089         m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBox));
4090
4091     m_overflow->addVisualOverflow(rect);
4092 }
4093
4094 void RenderBox::addContentsVisualOverflow(const LayoutRect& rect)
4095 {
4096     if (!hasOverflowClip()) {
4097         addVisualOverflow(rect);
4098         return;
4099     }
4100
4101     if (!m_overflow)
4102         m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBoxRect()));
4103     m_overflow->addContentsVisualOverflow(rect);
4104 }
4105
4106 void RenderBox::clearLayoutOverflow()
4107 {
4108     if (!m_overflow)
4109         return;
4110
4111     if (!hasVisualOverflow() && contentsVisualOverflowRect().isEmpty()) {
4112         clearAllOverflows();
4113         return;
4114     }
4115
4116     m_overflow->setLayoutOverflow(noOverflowRect());
4117 }
4118
4119 inline static bool percentageLogicalHeightIsResolvable(const RenderBox* box)
4120 {
4121     return RenderBox::percentageLogicalHeightIsResolvableFromBlock(box->containingBlock(), box->isOutOfFlowPositioned());
4122 }
4123
4124 bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* containingBlock, bool isOutOfFlowPositioned)
4125 {
4126     // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
4127     // block that may have a specified height and then use it. In strict mode, this violates the
4128     // specification, which states that percentage heights just revert to auto if the containing
4129     // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
4130     // only at explicit containers.
4131     const RenderBlock* cb = containingBlock;
4132     bool inQuirksMode = cb->document().inQuirksMode();
4133     while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style()->logicalHeight().isAuto()) {
4134         if (!inQuirksMode && !cb->isAnonymousBlock())
4135             break;
4136         cb = cb->containingBlock();
4137     }
4138
4139     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
4140     // explicitly specified that can be used for any percentage computations.
4141     // FIXME: We can't just check top/bottom here.
4142     // https://bugs.webkit.org/show_bug.cgi?id=46500
4143     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
4144
4145     // Table cells violate what the CSS spec says to do with heights.  Basically we
4146     // don't care if the cell specified a height or not.  We just always make ourselves
4147     // be a percentage of the cell's current content height.
4148     if (cb->isTableCell())
4149         return true;
4150
4151     // Otherwise we only use our percentage height if our containing block had a specified
4152     // height.
4153     if (cb->style()->logicalHeight().isFixed())
4154         return true;
4155     if (cb->style()->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight)
4156         return percentageLogicalHeightIsResolvableFromBlock(cb->containingBlock(), cb->isOutOfFlowPositioned());
4157     if (cb->isRenderView() || inQuirksMode || isOutOfFlowPositionedWithSpecifiedHeight)
4158         return true;
4159     if (cb->isDocumentElement() && isOutOfFlowPositioned) {
4160         // Match the positioned objects behavior, which is that positioned objects will fill their viewport
4161         // always.  Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
4162         return true;
4163     }
4164
4165     return false;
4166 }
4167
4168 bool RenderBox::hasUnsplittableScrollingOverflow() const
4169 {
4170     // We will paginate as long as we don't scroll overflow in the pagination direction.
4171     bool isHorizontal = isHorizontalWritingMode();
4172     if ((isHorizontal && !scrollsOverflowY()) || (!isHorizontal && !scrollsOverflowX()))
4173         return false;
4174
4175     // We do have overflow. We'll still be willing to paginate as long as the block
4176     // has auto logical height, auto or undefined max-logical-height and a zero or auto min-logical-height.
4177     // Note this is just a heuristic, and it's still possible to have overflow under these
4178     // conditions, but it should work out to be good enough for common cases. Paginating overflow
4179     // with scrollbars present is not the end of the world and is what we used to do in the old model anyway.
4180     return !style()->logicalHeight().isIntrinsicOrAuto()
4181         || (!style()->logicalMaxHeight().isIntrinsicOrAuto() && !style()->logicalMaxHeight().isMaxSizeNone() && (!style()->logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this)))
4182         || (!style()->logicalMinHeight().isIntrinsicOrAuto() && style()->logicalMinHeight().isPositive() && (!style()->logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this)));
4183 }
4184
4185 bool RenderBox::isUnsplittableForPagination() const
4186 {
4187     return isReplaced() || hasUnsplittableScrollingOverflow() || (parent() && isWritingModeRoot());
4188 }
4189
4190 LayoutUnit RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
4191 {
4192     if (isReplaced())
4193         return direction == HorizontalLine ? m_marginBox.top() + height() + m_marginBox.bottom() : m_marginBox.right() + width() + m_marginBox.left();
4194     return 0;
4195 }
4196
4197 int RenderBox::baselinePosition(FontBaseline baselineType, bool /*firstLine*/, LineDirectionMode direction, LinePositionMode linePositionMode) const
4198 {
4199     ASSERT(linePositionMode == PositionOnContainingLine);
4200     if (isReplaced()) {
4201         int result = direction == HorizontalLine ? m_marginBox.top() + height() + m_marginBox.bottom() : m_marginBox.right() + width() + m_marginBox.left();
4202         if (baselineType == AlphabeticBaseline)
4203             return result;
4204         return result - result / 2;
4205     }
4206     return 0;
4207 }
4208
4209
4210 RenderLayer* RenderBox::enclosingFloatPaintingLayer() const
4211 {
4212     const RenderObject* curr = this;
4213     while (curr) {
4214         RenderLayer* layer = curr->hasLayer() && curr->isBox() ? toRenderBox(curr)->layer() : 0;
4215         if (layer && layer->isSelfPaintingLayer())
4216             return layer;
4217         curr = curr->parent();
4218     }
4219     return 0;
4220 }
4221
4222 LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const
4223 {
4224     LayoutRect rect = visualOverflowRectForPropagation(parentStyle);
4225     if (!parentStyle->isHorizontalWritingMode())
4226         return rect.transposedRect();
4227     return rect;
4228 }
4229
4230 LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const
4231 {
4232     // If the writing modes of the child and parent match, then we don't have to
4233     // do anything fancy. Just return the result.
4234     LayoutRect rect = visualOverflowRect();
4235     if (parentStyle->writingMode() == style()->writingMode())
4236         return rect;
4237
4238     // We are putting ourselves into our parent's coordinate space.  If there is a flipped block mismatch
4239     // in a particular axis, then we have to flip the rect along that axis.
4240     if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
4241         rect.setX(width() - rect.maxX());
4242     else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
4243         rect.setY(height() - rect.maxY());
4244
4245     return rect;
4246 }
4247
4248 LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const
4249 {
4250     LayoutRect rect = layoutOverflowRectForPropagation(parentStyle);
4251     if (!parentStyle->isHorizontalWritingMode())
4252         return rect.transposedRect();
4253     return rect;
4254 }
4255
4256 LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const
4257 {
4258     // Only propagate interior layout overflow if we don't clip it.
4259     LayoutRect rect = borderBoxRect();
4260     // We want to include the margin, but only when it adds height. Quirky margins don't contribute height
4261     // nor do the margins of self-collapsing blocks.
4262     if (!style()->hasMarginAfterQuirk() && !isSelfCollapsingBlock())
4263         rect.expand(isHorizontalWritingMode() ? LayoutSize(LayoutUnit(), marginAfter()) : LayoutSize(marginAfter(), LayoutUnit()));
4264
4265     if (!hasOverflowClip())
4266         rect.unite(layoutOverflowRect());
4267
4268     bool hasTransform = hasLayer() && layer()->transform();
4269     if (isRelPositioned() || hasTransform) {
4270         // If we are relatively positioned or if we have a transform, then we have to convert
4271         // this rectangle into physical coordinates, apply relative positioning and transforms
4272         // to it, and then convert it back.
4273         flipForWritingMode(rect);
4274
4275         if (hasTransform)
4276             rect = layer()->currentTransform().mapRect(rect);
4277
4278         if (isRelPositioned())
4279             rect.move(offsetForInFlowPosition());
4280
4281         // Now we need to flip back.
4282         flipForWritingMode(rect);
4283     }
4284
4285     // If the writing modes of the child and parent match, then we don't have to
4286     // do anything fancy. Just return the result.
4287     if (parentStyle->writingMode() == style()->writingMode())
4288         return rect;
4289
4290     // We are putting ourselves into our parent's coordinate space.  If there is a flipped block mismatch
4291     // in a particular axis, then we have to flip the rect along that axis.
4292     if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
4293         rect.setX(width() - rect.maxX());
4294     else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
4295         rect.setY(height() - rect.maxY());
4296
4297     return rect;
4298 }
4299
4300 LayoutRect RenderBox::noOverflowRect() const
4301 {
4302     // Because of the special coordinate system used for overflow rectangles and many other
4303     // rectangles (not quite logical, not quite physical), we need to flip the block progression
4304     // coordinate in vertical-rl and horizontal-bt writing modes. In other words, the rectangle
4305     // returned is physical, except for the block direction progression coordinate (y in horizontal
4306     // writing modes, x in vertical writing modes), which is always "logical top". Apart from the
4307     // flipping, this method does the same as clientBoxRect().
4308
4309     const int scrollBarWidth = verticalScrollbarWidth();
4310     const int scrollBarHeight = horizontalScrollbarHeight();
4311     LayoutUnit left = borderLeft() + (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollBarWidth : 0);
4312     LayoutUnit top = borderTop();
4313     LayoutUnit right = borderRight();
4314     LayoutUnit bottom = borderBottom();
4315     LayoutRect rect(left, top, width() - left - right, height() - top - bottom);
4316     flipForWritingMode(rect);
4317     // Subtract space occupied by scrollbars. Order is important here: first flip, then subtract
4318     // scrollbars. This may seem backwards and weird, since one would think that a horizontal
4319     // scrollbar at the physical bottom in horizontal-bt ought to be at the logical top (physical
4320     // bottom), between the logical top (physical bottom) border and the logical top (physical
4321     // bottom) padding. But this is how the rest of the code expects us to behave. This is highly
4322     // related to https://bugs.webkit.org/show_bug.cgi?id=76129
4323     // FIXME: when the above mentioned bug is fixed, it should hopefully be possible to call
4324     // clientBoxRect() or paddingBoxRect() in this method, rather than fiddling with the edges on
4325     // our own.
4326     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
4327         rect.contract(0, scrollBarHeight);
4328     else
4329         rect.contract(scrollBarWidth, scrollBarHeight);
4330     return rect;
4331 }
4332
4333 LayoutUnit RenderBox::offsetLeft() const
4334 {
4335     return adjustedPositionRelativeToOffsetParent(topLeftLocation()).x();
4336 }
4337
4338 LayoutUnit RenderBox::offsetTop() const
4339 {
4340     return adjustedPositionRelativeToOffsetParent(topLeftLocation()).y();
4341 }
4342
4343 LayoutPoint RenderBox::flipForWritingModeForChild(const RenderBox* child, const LayoutPoint& point) const
4344 {
4345     if (!style()->isFlippedBlocksWritingMode())
4346         return point;
4347
4348     // The child is going to add in its x() and y(), so we have to make sure it ends up in
4349     // the right place.
4350     if (isHorizontalWritingMode())
4351         return LayoutPoint(point.x(), point.y() + height() - child->height() - (2 * child->y()));
4352     return LayoutPoint(point.x() + width() - child->width() - (2 * child->x()), point.y());
4353 }
4354
4355 void RenderBox::flipForWritingMode(LayoutRect& rect) const
4356 {
4357     if (!style()->isFlippedBlocksWritingMode())
4358         return;
4359
4360     if (isHorizontalWritingMode())
4361         rect.setY(height() - rect.maxY());
4362     else
4363         rect.setX(width() - rect.maxX());
4364 }
4365
4366 LayoutUnit RenderBox::flipForWritingMode(LayoutUnit position) const
4367 {
4368     if (!style()->isFlippedBlocksWritingMode())
4369         return position;
4370     return logicalHeight() - position;
4371 }
4372
4373 LayoutPoint RenderBox::flipForWritingMode(const LayoutPoint& position) const
4374 {
4375     if (!style()->isFlippedBlocksWritingMode())
4376         return position;
4377     return isHorizontalWritingMode() ? LayoutPoint(position.x(), height() - position.y()) : LayoutPoint(width() - position.x(), position.y());
4378 }
4379
4380 LayoutPoint RenderBox::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
4381 {
4382     if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
4383         return flipForWritingMode(point);
4384     return toRenderBlock(this)->flipForWritingModeIncludingColumns(point);
4385 }
4386
4387 LayoutSize RenderBox::flipForWritingMode(const LayoutSize& offset) const
4388 {
4389     if (!style()->isFlippedBlocksWritingMode())
4390         return offset;
4391     return isHorizontalWritingMode() ? LayoutSize(offset.width(), height() - offset.height()) : LayoutSize(width() - offset.width(), offset.height());
4392 }
4393
4394 FloatPoint RenderBox::flipForWritingMode(const FloatPoint& position) const
4395 {
4396     if (!style()->isFlippedBlocksWritingMode())
4397         return position;
4398     return isHorizontalWritingMode() ? FloatPoint(position.x(), height() - position.y()) : FloatPoint(width() - position.x(), position.y());
4399 }
4400
4401 void RenderBox::flipForWritingMode(FloatRect& rect) const
4402 {
4403     if (!style()->isFlippedBlocksWritingMode())
4404         return;
4405
4406     if (isHorizontalWritingMode())
4407         rect.setY(height() - rect.maxY());
4408     else
4409         rect.setX(width() - rect.maxX());
4410 }
4411
4412 LayoutPoint RenderBox::topLeftLocation() const
4413 {
4414     RenderBlock* containerBlock = containingBlock();
4415     if (!containerBlock || containerBlock == this)
4416         return location();
4417     return containerBlock->flipForWritingModeForChild(this, location());
4418 }
4419
4420 LayoutSize RenderBox::topLeftLocationOffset() const
4421 {
4422     RenderBlock* containerBlock = containingBlock();
4423     if (!containerBlock || containerBlock == this)
4424         return locationOffset();
4425
4426     LayoutRect rect(frameRect());
4427     containerBlock->flipForWritingMode(rect); // FIXME: This is wrong if we are an absolutely positioned object enclosed by a relative-positioned inline.
4428     return LayoutSize(rect.x(), rect.y());
4429 }
4430
4431 bool RenderBox::hasRelativeLogicalHeight() const
4432 {
4433     return style()->logicalHeight().isPercent()
4434         || style()->logicalMinHeight().isPercent()
4435         || style()->logicalMaxHeight().isPercent();
4436 }
4437
4438 static void markBoxForRelayoutAfterSplit(RenderBox* box)
4439 {
4440     // FIXME: The table code should handle that automatically. If not,
4441     // we should fix it and remove the table part checks.
4442     if (box->isTable()) {
4443         // Because we may have added some sections with already computed column structures, we need to
4444         // sync the table structure with them now. This avoids crashes when adding new cells to the table.
4445         toRenderTable(box)->forceSectionsRecalc();
4446     } else if (box->isTableSection())
4447         toRenderTableSection(box)->setNeedsCellRecalc();
4448
4449     box->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
4450 }
4451
4452 RenderObject* RenderBox::splitAnonymousBoxesAroundChild(RenderObject* beforeChild)
4453 {
4454     bool didSplitParentAnonymousBoxes = false;
4455
4456     while (beforeChild->parent() != this) {
4457         RenderBox* boxToSplit = toRenderBox(beforeChild->parent());
4458         if (boxToSplit->slowFirstChild() != beforeChild && boxToSplit->isAnonymous()) {
4459             didSplitParentAnonymousBoxes = true;
4460
4461             // We have to split the parent box into two boxes and move children
4462             // from |beforeChild| to end into the new post box.
4463             RenderBox* postBox = boxToSplit->createAnonymousBoxWithSameTypeAs(this);
4464             postBox->setChildrenInline(boxToSplit->childrenInline());
4465             RenderBox* parentBox = toRenderBox(boxToSplit->parent());
4466             // We need to invalidate the |parentBox| before inserting the new node
4467             // so that the table paint invalidation logic knows the structure is dirty.
4468             // See for example RenderTableCell:clippedOverflowRectForPaintInvalidation.
4469             markBoxForRelayoutAfterSplit(parentBox);
4470             parentBox->virtualChildren()->insertChildNode(parentBox, postBox, boxToSplit->nextSibling());
4471             boxToSplit->moveChildrenTo(postBox, beforeChild, 0, true);
4472
4473             markBoxForRelayoutAfterSplit(boxToSplit);
4474             markBoxForRelayoutAfterSplit(postBox);
4475
4476             beforeChild = postBox;
4477         } else
4478             beforeChild = boxToSplit;
4479     }
4480
4481     if (didSplitParentAnonymousBoxes)
4482         markBoxForRelayoutAfterSplit(this);
4483
4484     ASSERT(beforeChild->parent() == this);
4485     return beforeChild;
4486 }
4487
4488 LayoutUnit RenderBox::offsetFromLogicalTopOfFirstPage() const
4489 {
4490     LayoutState* layoutState = view()->layoutState();
4491     if (layoutState && !layoutState->isPaginated())
4492         return 0;
4493
4494     if (!layoutState && !flowThreadContainingBlock())
4495         return 0;
4496
4497     RenderBlock* containerBlock = containingBlock();
4498     return containerBlock->offsetFromLogicalTopOfFirstPage() + logicalTop();
4499 }
4500
4501 void RenderBox::savePreviousBorderBoxSizeIfNeeded()
4502 {
4503     // If m_rareData is already created, always save.
4504     if (!m_rareData) {
4505         LayoutSize paintInvalidationSize = previousPaintInvalidationRect().size();
4506
4507         // Don't save old border box size if the paint rect is empty because we'll
4508         // full invalidate once the paint rect becomes non-empty.
4509         if (paintInvalidationSize.isEmpty())
4510             return;
4511
4512         // Don't save old border box size if we can use size of the old paint rect
4513         // as the old border box size in the next invalidation.
4514         if (paintInvalidationSize == size())
4515             return;
4516
4517         // We need the old border box size only when the box has background or box decorations.
4518         if (!style()->hasBackground() && !style()->hasBoxDecorations())
4519             return;
4520     }
4521
4522     ensureRareData().m_previousBorderBoxSize = size();
4523 }
4524
4525 LayoutSize RenderBox::computePreviousBorderBoxSize(const LayoutSize& previousBoundsSize) const
4526 {
4527     // PreviousBorderBoxSize is only valid when there is background or box decorations.
4528     ASSERT(style()->hasBackground() || style()->hasBoxDecorations());
4529
4530     if (m_rareData && m_rareData->m_previousBorderBoxSize.width() != -1)
4531         return m_rareData->m_previousBorderBoxSize;
4532
4533     // We didn't save the old border box size because it was the same as the size of oldBounds.
4534     return previousBoundsSize;
4535 }
4536
4537 } // namespace blink