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