9e1a5a211eed19f51857fe271bb55d7ac851f7f1
[WebKit-https.git] / Source / WebCore / 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-2010, 2015 Apple Inc. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "RenderBox.h"
27
28 #include "CSSFontSelector.h"
29 #include "Chrome.h"
30 #include "ChromeClient.h"
31 #include "Document.h"
32 #include "EventHandler.h"
33 #include "FloatQuad.h"
34 #include "FloatRoundedRect.h"
35 #include "Frame.h"
36 #include "FrameView.h"
37 #include "GraphicsContext.h"
38 #include "HTMLAnchorElement.h"
39 #include "HTMLBodyElement.h"
40 #include "HTMLButtonElement.h"
41 #include "HTMLFrameOwnerElement.h"
42 #include "HTMLHtmlElement.h"
43 #include "HTMLInputElement.h"
44 #include "HTMLLegendElement.h"
45 #include "HTMLNames.h"
46 #include "HTMLSelectElement.h"
47 #include "HTMLTextAreaElement.h"
48 #include "HitTestResult.h"
49 #include "InlineElementBox.h"
50 #include "MainFrame.h"
51 #include "Page.h"
52 #include "PaintInfo.h"
53 #include "RenderBoxRegionInfo.h"
54 #include "RenderChildIterator.h"
55 #include "RenderDeprecatedFlexibleBox.h"
56 #include "RenderFlexibleBox.h"
57 #include "RenderGeometryMap.h"
58 #include "RenderInline.h"
59 #include "RenderIterator.h"
60 #include "RenderLayer.h"
61 #include "RenderLayerCompositor.h"
62 #include "RenderNamedFlowFragment.h"
63 #include "RenderNamedFlowThread.h"
64 #include "RenderTableCell.h"
65 #include "RenderTheme.h"
66 #include "RenderView.h"
67 #include "ScrollAnimator.h"
68 #include "ScrollbarTheme.h"
69 #include "TransformState.h"
70 #include "htmlediting.h"
71 #include <algorithm>
72 #include <math.h>
73 #include <wtf/StackStats.h>
74
75 #if PLATFORM(IOS)
76 #include "Settings.h"
77 #endif
78
79 namespace WebCore {
80
81 struct SameSizeAsRenderBox : public RenderBoxModelObject {
82     virtual ~SameSizeAsRenderBox() { }
83     LayoutRect frameRect;
84     LayoutBoxExtent marginBox;
85     LayoutUnit preferredLogicalWidths[2];
86     void* pointers[2];
87 };
88
89 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
90
91 using namespace HTMLNames;
92
93 // Used by flexible boxes when flexing this element and by table cells.
94 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
95 static OverrideSizeMap* gOverrideHeightMap = nullptr;
96 static OverrideSizeMap* gOverrideWidthMap = nullptr;
97
98 #if ENABLE(CSS_GRID_LAYOUT)
99 // Used by grid elements to properly size their grid items.
100 typedef WTF::HashMap<const RenderBox*, Optional<LayoutUnit>> OverrideOptionalSizeMap;
101 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
102 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
103 static OverrideSizeMap* gExtraInlineOffsetMap = nullptr;
104 static OverrideSizeMap* gExtraBlockOffsetMap = nullptr;
105 #endif
106
107 // Size of border belt for autoscroll. When mouse pointer in border belt,
108 // autoscroll is started.
109 static const int autoscrollBeltSize = 20;
110 static const unsigned backgroundObscurationTestMaxDepth = 4;
111
112 bool RenderBox::s_hadOverflowClip = false;
113
114 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
115 {
116     ASSERT(bodyElementRenderer->isBody());
117     // The <body> only paints its background if the root element has defined a background independent of the body,
118     // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
119     auto documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
120     return documentElementRenderer
121         && !documentElementRenderer->hasBackground()
122         && (documentElementRenderer == bodyElementRenderer->parent());
123 }
124
125 RenderBox::RenderBox(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
126     : RenderBoxModelObject(element, WTFMove(style), baseTypeFlags)
127     , m_minPreferredLogicalWidth(-1)
128     , m_maxPreferredLogicalWidth(-1)
129     , m_inlineBoxWrapper(nullptr)
130 {
131     setIsBox();
132 }
133
134 RenderBox::RenderBox(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
135     : RenderBoxModelObject(document, WTFMove(style), baseTypeFlags)
136     , m_minPreferredLogicalWidth(-1)
137     , m_maxPreferredLogicalWidth(-1)
138     , m_inlineBoxWrapper(nullptr)
139 {
140     setIsBox();
141 }
142
143 RenderBox::~RenderBox()
144 {
145     if (frame().eventHandler().autoscrollRenderer() == this)
146         frame().eventHandler().stopAutoscrollTimer(true);
147
148     clearOverrideSize();
149 #if ENABLE(CSS_GRID_LAYOUT)
150     clearContainingBlockOverrideSize();
151     clearExtraInlineAndBlockOffests();
152 #endif
153
154     RenderBlock::removePercentHeightDescendantIfNeeded(*this);
155
156 #if ENABLE(CSS_SHAPES)
157     ShapeOutsideInfo::removeInfo(*this);
158 #endif
159
160     view().unscheduleLazyRepaint(*this);
161     if (hasControlStatesForRenderer(this))
162         removeControlStatesForRenderer(this);
163 }
164
165 RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const
166 {
167     RenderFlowThread* flowThread = flowThreadContainingBlock();
168
169     ASSERT(isRenderView() || (region && flowThread));
170     if (isRenderView())
171         return region;
172
173     // We need to clamp to the block, since we want any lines or blocks that overflow out of the
174     // logical top or logical bottom of the block to size as though the border box in the first and
175     // last regions extended infinitely. Otherwise the lines are going to size according to the regions
176     // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
177     RenderRegion* startRegion = nullptr;
178     RenderRegion* endRegion = nullptr;
179     if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion))
180         return region;
181
182     if (region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
183         return startRegion;
184     if (region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
185         return endRegion;
186
187     return region;
188 }
189
190 bool RenderBox::hasRegionRangeInFlowThread() const
191 {
192     RenderFlowThread* flowThread = flowThreadContainingBlock();
193     if (!flowThread || !flowThread->hasValidRegionInfo())
194         return false;
195
196     return flowThread->hasCachedRegionRangeForBox(this);
197 }
198
199 LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const
200 {
201     if (!region)
202         return clientBoxRect();
203
204     LayoutRect clientBox = borderBoxRectInRegion(region);
205     clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
206     clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
207
208     return clientBox;
209 }
210
211 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
212 {
213     if (!region)
214         return borderBoxRect();
215
216     RenderFlowThread* flowThread = flowThreadContainingBlock();
217     if (!flowThread)
218         return borderBoxRect();
219
220     RenderRegion* startRegion = nullptr;
221     RenderRegion* endRegion = nullptr;
222     if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) {
223         // FIXME: In a perfect world this condition should never happen.
224         return borderBoxRect();
225     }
226
227     ASSERT(flowThread->regionInRange(region, startRegion, endRegion));
228
229     // Compute the logical width and placement in this region.
230     RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
231     if (!boxInfo)
232         return borderBoxRect();
233
234     // We have cached insets.
235     LayoutUnit logicalWidth = boxInfo->logicalWidth();
236     LayoutUnit logicalLeft = boxInfo->logicalLeft();
237
238     // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
239     // FIXME: Doesn't work right with perpendicular writing modes.
240     const RenderBlock* currentBox = containingBlock();
241     RenderBoxRegionInfo* currentBoxInfo = isRenderFlowThread() ? nullptr : currentBox->renderBoxRegionInfo(region);
242     while (currentBoxInfo && currentBoxInfo->isShifted()) {
243         if (currentBox->style().direction() == LTR)
244             logicalLeft += currentBoxInfo->logicalLeft();
245         else
246             logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
247
248         // Once we reach the fragmentation container we should stop.
249         if (currentBox->isRenderFlowThread())
250             break;
251
252         currentBox = currentBox->containingBlock();
253         if (!currentBox)
254             break;
255         region = currentBox->clampToStartAndEndRegions(region);
256         currentBoxInfo = currentBox->renderBoxRegionInfo(region);
257     }
258
259     if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
260         delete boxInfo;
261
262     if (isHorizontalWritingMode())
263         return LayoutRect(logicalLeft, 0, logicalWidth, height());
264     return LayoutRect(0, logicalLeft, width(), logicalWidth);
265 }
266
267 static RenderBlockFlow* outermostBlockContainingFloatingObject(RenderBox& box)
268 {
269     ASSERT(box.isFloating());
270     RenderBlockFlow* parentBlock = nullptr;
271     for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(box)) {
272         if (ancestor.isRenderView())
273             break;
274         if (!parentBlock || ancestor.containsFloat(box))
275             parentBlock = &ancestor;
276     }
277     return parentBlock;
278 }
279
280 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
281 {
282     ASSERT(isFloatingOrOutOfFlowPositioned());
283
284     if (documentBeingDestroyed())
285         return;
286
287     if (isFloating()) {
288         if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject(*this)) {
289             parentBlock->markSiblingsWithFloatsForLayout(this);
290             parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
291         }
292     }
293
294     if (isOutOfFlowPositioned())
295         RenderBlock::removePositionedObject(*this);
296 }
297
298 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
299 {
300     s_hadOverflowClip = hasOverflowClip();
301
302     const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
303     if (oldStyle) {
304         // The background of the root element or the body element could propagate up to
305         // the canvas. Issue full repaint, when our style changes substantially.
306         if (diff >= StyleDifferenceRepaint && (isDocumentElementRenderer() || isBody())) {
307             view().repaintRootContents();
308             if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
309                 view().compositor().rootFixedBackgroundsChanged();
310         }
311         
312         // When a layout hint happens and an object's position style changes, we have to do a layout
313         // to dirty the render tree using the old position value now.
314         if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
315             markContainingBlocksForLayout();
316             if (oldStyle->position() == StaticPosition)
317                 repaint();
318             else if (newStyle.hasOutOfFlowPosition())
319                 parent()->setChildNeedsLayout();
320             if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
321                 removeFloatingOrPositionedChildFromBlockLists();
322         }
323     } else if (isBody())
324         view().repaintRootContents();
325
326 #if ENABLE(CSS_SCROLL_SNAP)
327     if (!newStyle.scrollSnapCoordinates().isEmpty() || (oldStyle && !oldStyle->scrollSnapCoordinates().isEmpty())) {
328         if (newStyle.scrollSnapCoordinates().isEmpty())
329             view().unregisterBoxWithScrollSnapCoordinates(*this);
330         else
331             view().registerBoxWithScrollSnapCoordinates(*this);
332     }
333 #endif
334
335     RenderBoxModelObject::styleWillChange(diff, newStyle);
336 }
337
338 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
339 {
340     // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
341     // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
342     // writing mode value before style change here.
343     bool oldHorizontalWritingMode = isHorizontalWritingMode();
344
345     RenderBoxModelObject::styleDidChange(diff, oldStyle);
346
347     const RenderStyle& newStyle = style();
348     if (needsLayout() && oldStyle) {
349         RenderBlock::removePercentHeightDescendantIfNeeded(*this);
350
351         // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
352         // when the positioned object's margin-before is changed. In this case the parent has to get a layout in order to run margin collapsing
353         // to determine the new static position.
354         if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
355             && parent() && !parent()->normalChildNeedsLayout())
356             parent()->setChildNeedsLayout();
357     }
358
359     if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
360         && oldHorizontalWritingMode != isHorizontalWritingMode())
361         RenderBlock::clearPercentHeightDescendantsFrom(*this);
362
363     // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
364     // new zoomed coordinate space.
365     if (hasOverflowClip() && layer() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
366         if (int left = layer()->scrollOffset().x()) {
367             left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
368             layer()->scrollToXOffset(left);
369         }
370         if (int top = layer()->scrollOffset().y()) {
371             top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
372             layer()->scrollToYOffset(top);
373         }
374     }
375
376     // Our opaqueness might have changed without triggering layout.
377     if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
378         auto parentToInvalidate = parent();
379         for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
380             parentToInvalidate->invalidateBackgroundObscurationStatus();
381             parentToInvalidate = parentToInvalidate->parent();
382         }
383     }
384
385     bool isBodyRenderer = isBody();
386     bool isDocElementRenderer = isDocumentElementRenderer();
387
388     if (isDocElementRenderer || isBodyRenderer) {
389         // Propagate the new writing mode and direction up to the RenderView.
390         auto* documentElementRenderer = document().documentElement()->renderer();
391         auto& viewStyle = view().mutableStyle();
392         bool viewChangedWritingMode = false;
393         bool rootStyleChanged = false;
394         bool viewStyleChanged = false;
395         auto* rootRenderer = isBodyRenderer ? documentElementRenderer : nullptr;
396         if (viewStyle.direction() != newStyle.direction() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetDirection())) {
397             viewStyle.setDirection(newStyle.direction());
398             viewStyleChanged = true;
399             if (isBodyRenderer) {
400                 rootRenderer->mutableStyle().setDirection(newStyle.direction());
401                 rootStyleChanged = true;
402             }
403             setNeedsLayoutAndPrefWidthsRecalc();
404         }
405
406         if (viewStyle.writingMode() != newStyle.writingMode() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetWritingMode())) {
407             viewStyle.setWritingMode(newStyle.writingMode());
408             viewChangedWritingMode = true;
409             viewStyleChanged = true;
410             view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
411             view().markAllDescendantsWithFloatsForLayout();
412             if (isBodyRenderer) {
413                 rootStyleChanged = true;
414                 rootRenderer->mutableStyle().setWritingMode(newStyle.writingMode());
415                 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
416             }
417             setNeedsLayoutAndPrefWidthsRecalc();
418         }
419
420         view().frameView().recalculateScrollbarOverlayStyle();
421         
422         const Pagination& pagination = view().frameView().pagination();
423         if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) {
424             viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
425             if (view().multiColumnFlowThread())
426                 view().updateColumnProgressionFromStyle(viewStyle);
427         }
428         
429         if (viewStyleChanged && view().multiColumnFlowThread())
430             view().updateStylesForColumnChildren();
431         
432         if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlowThread())
433             downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
434         
435         if (isBodyRenderer && pagination.mode != Pagination::Unpaginated && frame().page()->paginationLineGridEnabled()) {
436             // Propagate the body font back up to the RenderView and use it as
437             // the basis of the grid.
438             if (newStyle.fontDescription() != view().style().fontDescription()) {
439                 view().mutableStyle().setFontDescription(newStyle.fontDescription());
440                 view().mutableStyle().fontCascade().update(&document().fontSelector());
441             }
442         }
443
444         if (diff != StyleDifferenceEqual)
445             view().compositor().rootOrBodyStyleChanged(*this, oldStyle);
446     }
447
448 #if ENABLE(CSS_SHAPES)
449     if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
450         updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
451 #endif
452 }
453
454 void RenderBox::willBeRemovedFromTree()
455 {
456 #if ENABLE(CSS_SCROLL_SNAP)
457     if (hasInitializedStyle() && !style().scrollSnapCoordinates().isEmpty())
458         view().unregisterBoxWithScrollSnapCoordinates(*this);
459 #endif
460     
461     RenderBoxModelObject::willBeRemovedFromTree();
462 }
463     
464
465 #if ENABLE(CSS_SHAPES)
466 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
467 {
468     const ShapeValue* shapeOutside = style.shapeOutside();
469     const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
470
471     Length shapeMargin = style.shapeMargin();
472     Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
473
474     float shapeImageThreshold = style.shapeImageThreshold();
475     float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
476
477     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
478     if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
479         return;
480
481     if (!shapeOutside)
482         ShapeOutsideInfo::removeInfo(*this);
483     else
484         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
485
486     if (shapeOutside || shapeOutside != oldShapeOutside)
487         markShapeOutsideDependentsForLayout();
488 }
489 #endif
490
491 void RenderBox::updateFromStyle()
492 {
493     RenderBoxModelObject::updateFromStyle();
494
495     const RenderStyle& styleToUse = style();
496     bool isDocElementRenderer = isDocumentElementRenderer();
497     bool isViewObject = isRenderView();
498
499     // The root and the RenderView always paint their backgrounds/borders.
500     if (isDocElementRenderer || isViewObject)
501         setHasVisibleBoxDecorations(true);
502
503     setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
504
505     // We also handle <body> and <html>, whose overflow applies to the viewport.
506     if (styleToUse.overflowX() != OVISIBLE && !isDocElementRenderer && isRenderBlock()) {
507         bool boxHasOverflowClip = true;
508         if (isBody()) {
509             // Overflow on the body can propagate to the viewport under the following conditions.
510             // (1) The root element is <html>.
511             // (2) We are the primary <body> (can be checked by looking at document.body).
512             // (3) The root element has visible overflow.
513             if (is<HTMLHtmlElement>(*document().documentElement())
514                 && document().body() == element()
515                 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
516                 boxHasOverflowClip = false;
517             }
518         }
519         // Check for overflow clip.
520         // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
521         if (boxHasOverflowClip) {
522             if (!s_hadOverflowClip && hasRenderOverflow()) {
523                 // Erase the overflow.
524                 // Overflow changes have to result in immediate repaints of the entire layout overflow area because
525                 // repaints issued by removal of descendants get clipped using the updated style when they shouldn't.
526                 repaintRectangle(visualOverflowRect());
527                 repaintRectangle(layoutOverflowRect());
528             }
529             setHasOverflowClip();
530         }
531     }
532     setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty());
533     setHasReflection(styleToUse.boxReflect());
534 }
535
536 void RenderBox::layout()
537 {
538     StackStats::LayoutCheckPoint layoutCheckPoint;
539     ASSERT(needsLayout());
540
541     RenderObject* child = firstChild();
542     if (!child) {
543         clearNeedsLayout();
544         return;
545     }
546
547     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
548     while (child) {
549         if (child->needsLayout())
550             downcast<RenderElement>(*child).layout();
551         ASSERT(!child->needsLayout());
552         child = child->nextSibling();
553     }
554     statePusher.pop();
555     invalidateBackgroundObscurationStatus();
556     clearNeedsLayout();
557 }
558
559 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
560 // excluding border and scrollbar.
561 LayoutUnit RenderBox::clientWidth() const
562 {
563     return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
564 }
565
566 LayoutUnit RenderBox::clientHeight() const
567 {
568     return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
569 }
570
571 int RenderBox::scrollWidth() const
572 {
573     if (hasOverflowClip() && layer())
574         return layer()->scrollWidth();
575     // For objects with visible overflow, this matches IE.
576     // FIXME: Need to work right with writing modes.
577     if (style().isLeftToRightDirection()) {
578         // FIXME: This should use snappedIntSize() instead with absolute coordinates.
579         return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
580     }
581     return roundToInt(clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft()));
582 }
583
584 int RenderBox::scrollHeight() const
585 {
586     if (hasOverflowClip() && layer())
587         return layer()->scrollHeight();
588     // For objects with visible overflow, this matches IE.
589     // FIXME: Need to work right with writing modes.
590     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
591     return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
592 }
593
594 int RenderBox::scrollLeft() const
595 {
596     return hasOverflowClip() && layer() ? layer()->scrollPosition().x() : 0;
597 }
598
599 int RenderBox::scrollTop() const
600 {
601     return hasOverflowClip() && layer() ? layer()->scrollPosition().y() : 0;
602 }
603
604 static void setupWheelEventTestTrigger(RenderLayer& layer, Frame* frame)
605 {
606     if (!frame)
607         return;
608
609     Page* page = frame->page();
610     if (!page || !page->expectsWheelEventTriggers())
611         return;
612
613     layer.scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
614 }
615
616 void RenderBox::setScrollLeft(int newLeft)
617 {
618     if (!hasOverflowClip() || !layer())
619         return;
620     setupWheelEventTestTrigger(*layer(), document().frame());
621     layer()->scrollToXPosition(newLeft, RenderLayer::ScrollOffsetClamped);
622 }
623
624 void RenderBox::setScrollTop(int newTop)
625 {
626     if (!hasOverflowClip() || !layer())
627         return;
628     setupWheelEventTestTrigger(*layer(), document().frame());
629     layer()->scrollToYPosition(newTop, RenderLayer::ScrollOffsetClamped);
630 }
631
632 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
633 {
634     rects.append(snappedIntRect(accumulatedOffset, size()));
635 }
636
637 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
638 {
639     FloatRect localRect(0, 0, width(), height());
640
641     RenderFlowThread* flowThread = flowThreadContainingBlock();
642     if (flowThread && flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
643         return;
644
645     quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed));
646 }
647
648 void RenderBox::updateLayerTransform()
649 {
650     // Transform-origin depends on box size, so we need to update the layer transform after layout.
651     if (hasLayer())
652         layer()->updateTransform();
653 }
654
655 LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock& cb, RenderRegion* region) const
656 {
657     const RenderStyle& styleToUse = style();
658     if (!styleToUse.logicalMaxWidth().isUndefined())
659         logicalWidth = std::min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, region));
660     return std::max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, region));
661 }
662
663 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, Optional<LayoutUnit> intrinsicContentHeight) const
664 {
665     const RenderStyle& styleToUse = style();
666     if (!styleToUse.logicalMaxHeight().isUndefined()) {
667         if (Optional<LayoutUnit> maxH = computeLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
668             logicalHeight = std::min(logicalHeight, maxH.value());
669     }
670     if (Optional<LayoutUnit> computedLogicalHeight = computeLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
671         return std::max(logicalHeight, computedLogicalHeight.value());
672     return logicalHeight;
673 }
674
675 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, Optional<LayoutUnit> intrinsicContentHeight) const
676 {
677     const RenderStyle& styleToUse = style();
678     if (!styleToUse.logicalMaxHeight().isUndefined()) {
679         if (Optional<LayoutUnit> maxH = computeContentLogicalHeight(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
680             logicalHeight = std::min(logicalHeight, maxH.value());
681     }
682     if (Optional<LayoutUnit> computedContentLogicalHeight = computeContentLogicalHeight(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
683         return std::max(logicalHeight, computedContentLogicalHeight.value());
684     return logicalHeight;
685 }
686
687 RoundedRect::Radii RenderBox::borderRadii() const
688 {
689     auto& style = this->style();
690     LayoutRect bounds = frameRect();
691
692     unsigned borderLeft = style.borderLeftWidth();
693     unsigned borderTop = style.borderTopWidth();
694     bounds.moveBy(LayoutPoint(borderLeft, borderTop));
695     bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
696     return style.getRoundedBorderFor(bounds).radii();
697 }
698
699 LayoutRect RenderBox::contentBoxRect() const
700 {
701     LayoutUnit x = borderLeft() + paddingLeft();
702     if (shouldPlaceBlockDirectionScrollbarOnLeft())
703         x += verticalScrollbarWidth();
704     LayoutUnit y = borderTop() + paddingTop();
705     return LayoutRect(x, y, contentWidth(), contentHeight());
706 }
707
708 IntRect RenderBox::absoluteContentBox() const
709 {
710     // This is wrong with transforms and flipped writing modes.
711     IntRect rect = snappedIntRect(contentBoxRect());
712     FloatPoint absPos = localToAbsolute();
713     rect.move(absPos.x(), absPos.y());
714     return rect;
715 }
716
717 FloatQuad RenderBox::absoluteContentQuad() const
718 {
719     LayoutRect rect = contentBoxRect();
720     return localToAbsoluteQuad(FloatRect(rect));
721 }
722
723 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
724 {
725     LayoutRect box = borderBoundingBox();
726     adjustRectForOutlineAndShadow(box);
727
728     if (repaintContainer != this) {
729         FloatQuad containerRelativeQuad;
730         if (geometryMap)
731             containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
732         else
733             containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
734
735         box = LayoutRect(containerRelativeQuad.boundingBox());
736     }
737     
738     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
739     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
740     box.move(view().layoutDelta());
741
742     return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
743 }
744
745 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
746 {
747     if (!size().isEmpty())
748         rects.append(LayoutRect(additionalOffset, size()));
749 }
750
751 int RenderBox::reflectionOffset() const
752 {
753     if (!style().boxReflect())
754         return 0;
755     if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
756         return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
757     return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
758 }
759
760 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
761 {
762     if (!style().boxReflect())
763         return LayoutRect();
764
765     LayoutRect box = borderBoxRect();
766     LayoutRect result = r;
767     switch (style().boxReflect()->direction()) {
768         case ReflectionBelow:
769             result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
770             break;
771         case ReflectionAbove:
772             result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
773             break;
774         case ReflectionLeft:
775             result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
776             break;
777         case ReflectionRight:
778             result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
779             break;
780     }
781     return result;
782 }
783
784 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
785 {
786     return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
787 }
788
789 bool RenderBox::includeVerticalScrollbarSize() const
790 {
791     return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
792         && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
793 }
794
795 bool RenderBox::includeHorizontalScrollbarSize() const
796 {
797     return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
798         && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
799 }
800
801 int RenderBox::verticalScrollbarWidth() const
802 {
803     return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
804 }
805
806 int RenderBox::horizontalScrollbarHeight() const
807 {
808     return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
809 }
810
811 int RenderBox::intrinsicScrollbarLogicalWidth() const
812 {
813     if (!hasOverflowClip())
814         return 0;
815
816     if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
817         ASSERT(layer() && layer()->hasVerticalScrollbar());
818         return verticalScrollbarWidth();
819     }
820
821     if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
822         ASSERT(layer() && layer()->hasHorizontalScrollbar());
823         return horizontalScrollbarHeight();
824     }
825
826     return 0;
827 }
828
829 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
830 {
831     RenderLayer* boxLayer = layer();
832     if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
833         if (stopElement)
834             *stopElement = element();
835
836         return true;
837     }
838
839     return false;
840 }
841
842 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
843 {
844     if (scrollLayer(direction, granularity, multiplier, stopElement))
845         return true;
846
847     if (stopElement && *stopElement && *stopElement == element())
848         return true;
849
850     RenderBlock* nextScrollBlock = containingBlock();
851     if (is<RenderNamedFlowThread>(nextScrollBlock)) {
852         ASSERT(startBox);
853         nextScrollBlock = downcast<RenderNamedFlowThread>(*nextScrollBlock).fragmentFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox);
854     }
855
856     if (nextScrollBlock && !nextScrollBlock->isRenderView())
857         return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
858
859     return false;
860 }
861
862 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
863 {
864     bool scrolled = false;
865     
866     RenderLayer* l = layer();
867     if (l) {
868 #if PLATFORM(COCOA)
869         // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
870         if (granularity == ScrollByDocument)
871             scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
872 #endif
873         if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
874             scrolled = true;
875         
876         if (scrolled) {
877             if (stopElement)
878                 *stopElement = element();
879             return true;
880         }
881     }
882
883     if (stopElement && *stopElement && *stopElement == element())
884         return true;
885
886     RenderBlock* b = containingBlock();
887     if (b && !b->isRenderView())
888         return b->logicalScroll(direction, granularity, multiplier, stopElement);
889     return false;
890 }
891
892 bool RenderBox::canBeScrolledAndHasScrollableArea() const
893 {
894     return canBeProgramaticallyScrolled() && (hasHorizontalOverflow() || hasVerticalOverflow());
895 }
896
897 bool RenderBox::isScrollableOrRubberbandableBox() const
898 {
899     return canBeScrolledAndHasScrollableArea();
900 }
901
902 // FIXME: This is badly named. overflow:hidden can be programmatically scrolled, yet this returns false in that case.
903 bool RenderBox::canBeProgramaticallyScrolled() const
904 {
905     if (isRenderView())
906         return true;
907
908     if (!hasOverflowClip())
909         return false;
910
911     if (hasScrollableOverflowX() || hasScrollableOverflowY())
912         return true;
913
914     return element() && element()->hasEditableStyle();
915 }
916
917 bool RenderBox::usesCompositedScrolling() const
918 {
919     return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
920 }
921
922 void RenderBox::autoscroll(const IntPoint& position)
923 {
924     if (layer())
925         layer()->autoscroll(position);
926 }
927
928 // There are two kinds of renderer that can autoscroll.
929 bool RenderBox::canAutoscroll() const
930 {
931     if (isRenderView())
932         return view().frameView().isScrollable();
933
934     // Check for a box that can be scrolled in its own right.
935     if (canBeScrolledAndHasScrollableArea())
936         return true;
937
938     return false;
939 }
940
941 // If specified point is in border belt, returned offset denotes direction of
942 // scrolling.
943 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
944 {
945     IntRect box(absoluteBoundingBoxRect());
946     box.moveBy(view().frameView().scrollPosition());
947     IntRect windowBox = view().frameView().contentsToWindow(box);
948
949     IntPoint windowAutoscrollPoint = windowPoint;
950
951     if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
952         windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
953     else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
954         windowAutoscrollPoint.move(autoscrollBeltSize, 0);
955
956     if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
957         windowAutoscrollPoint.move(0, -autoscrollBeltSize);
958     else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
959         windowAutoscrollPoint.move(0, autoscrollBeltSize);
960
961     return windowAutoscrollPoint - windowPoint;
962 }
963
964 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
965 {
966     while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) {
967         if (is<RenderView>(*renderer) && renderer->document().ownerElement())
968             renderer = renderer->document().ownerElement()->renderer();
969         else
970             renderer = renderer->parent();
971     }
972
973     return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
974 }
975
976 void RenderBox::panScroll(const IntPoint& source)
977 {
978     if (layer())
979         layer()->panScrollFromPoint(source);
980 }
981
982 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
983 {
984     bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
985     return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
986 }
987
988 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
989 {
990     bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
991     return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
992 }
993
994 bool RenderBox::needsPreferredWidthsRecalculation() const
995 {
996     return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated();
997 }
998
999 ScrollPosition RenderBox::scrollPosition() const
1000 {
1001     if (!hasOverflowClip())
1002         return { 0, 0 };
1003
1004     ASSERT(hasLayer());
1005     return layer()->scrollPosition();
1006 }
1007
1008 LayoutSize RenderBox::cachedSizeForOverflowClip() const
1009 {
1010     ASSERT(hasOverflowClip());
1011     ASSERT(hasLayer());
1012     return layer()->size();
1013 }
1014
1015 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
1016 {
1017     flipForWritingMode(paintRect);
1018     paintRect.moveBy(-scrollPosition()); // For overflow:auto/scroll/hidden.
1019
1020     // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
1021     if (usesCompositedScrolling()) {
1022         flipForWritingMode(paintRect);
1023         return;
1024     }
1025
1026     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
1027     // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1028     // anyway if its size does change.
1029     LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
1030     paintRect = intersection(paintRect, clipRect);
1031     flipForWritingMode(paintRect);
1032 }
1033
1034 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
1035 {
1036     minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1037     maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1038 }
1039
1040 LayoutUnit RenderBox::minPreferredLogicalWidth() const
1041 {
1042     if (preferredLogicalWidthsDirty()) {
1043 #ifndef NDEBUG
1044         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1045 #endif
1046         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1047     }
1048         
1049     return m_minPreferredLogicalWidth;
1050 }
1051
1052 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1053 {
1054     if (preferredLogicalWidthsDirty()) {
1055 #ifndef NDEBUG
1056         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1057 #endif
1058         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1059     }
1060         
1061     return m_maxPreferredLogicalWidth;
1062 }
1063
1064 bool RenderBox::hasOverrideLogicalContentHeight() const
1065 {
1066     return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1067 }
1068
1069 bool RenderBox::hasOverrideLogicalContentWidth() const
1070 {
1071     return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1072 }
1073
1074 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1075 {
1076     if (!gOverrideHeightMap)
1077         gOverrideHeightMap = new OverrideSizeMap();
1078     gOverrideHeightMap->set(this, height);
1079 }
1080
1081 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1082 {
1083     if (!gOverrideWidthMap)
1084         gOverrideWidthMap = new OverrideSizeMap();
1085     gOverrideWidthMap->set(this, width);
1086 }
1087
1088 void RenderBox::clearOverrideLogicalContentHeight()
1089 {
1090     if (gOverrideHeightMap)
1091         gOverrideHeightMap->remove(this);
1092 }
1093
1094 void RenderBox::clearOverrideLogicalContentWidth()
1095 {
1096     if (gOverrideWidthMap)
1097         gOverrideWidthMap->remove(this);
1098 }
1099
1100 void RenderBox::clearOverrideSize()
1101 {
1102     clearOverrideLogicalContentHeight();
1103     clearOverrideLogicalContentWidth();
1104 }
1105
1106 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1107 {
1108     ASSERT(hasOverrideLogicalContentWidth());
1109     return gOverrideWidthMap->get(this);
1110 }
1111
1112 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1113 {
1114     ASSERT(hasOverrideLogicalContentHeight());
1115     return gOverrideHeightMap->get(this);
1116 }
1117
1118 #if ENABLE(CSS_GRID_LAYOUT)
1119 Optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalWidth() const
1120 {
1121     ASSERT(hasOverrideContainingBlockLogicalWidth());
1122     return gOverrideContainingBlockLogicalWidthMap->get(this);
1123 }
1124
1125 Optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalHeight() const
1126 {
1127     ASSERT(hasOverrideContainingBlockLogicalHeight());
1128     return gOverrideContainingBlockLogicalHeightMap->get(this);
1129 }
1130
1131 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1132 {
1133     return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1134 }
1135
1136 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1137 {
1138     return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1139 }
1140
1141 void RenderBox::setOverrideContainingBlockContentLogicalWidth(Optional<LayoutUnit> logicalWidth)
1142 {
1143     if (!gOverrideContainingBlockLogicalWidthMap)
1144         gOverrideContainingBlockLogicalWidthMap = new OverrideOptionalSizeMap;
1145     gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1146 }
1147
1148 void RenderBox::setOverrideContainingBlockContentLogicalHeight(Optional<LayoutUnit> logicalHeight)
1149 {
1150     if (!gOverrideContainingBlockLogicalHeightMap)
1151         gOverrideContainingBlockLogicalHeightMap = new OverrideOptionalSizeMap;
1152     gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1153 }
1154
1155 void RenderBox::clearContainingBlockOverrideSize()
1156 {
1157     if (gOverrideContainingBlockLogicalWidthMap)
1158         gOverrideContainingBlockLogicalWidthMap->remove(this);
1159     clearOverrideContainingBlockContentLogicalHeight();
1160 }
1161
1162 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1163 {
1164     if (gOverrideContainingBlockLogicalHeightMap)
1165         gOverrideContainingBlockLogicalHeightMap->remove(this);
1166 }
1167
1168 LayoutUnit RenderBox::extraInlineOffset() const
1169 {
1170     return gExtraInlineOffsetMap ? gExtraInlineOffsetMap->get(this) : LayoutUnit();
1171 }
1172
1173 LayoutUnit RenderBox::extraBlockOffset() const
1174 {
1175     return gExtraBlockOffsetMap ? gExtraBlockOffsetMap->get(this) : LayoutUnit();
1176 }
1177
1178 void RenderBox::setExtraInlineOffset(LayoutUnit inlineOffest)
1179 {
1180     if (!gExtraInlineOffsetMap)
1181         gExtraInlineOffsetMap = new OverrideSizeMap;
1182     gExtraInlineOffsetMap->set(this, inlineOffest);
1183 }
1184
1185 void RenderBox::setExtraBlockOffset(LayoutUnit blockOffest)
1186 {
1187     if (!gExtraBlockOffsetMap)
1188         gExtraBlockOffsetMap = new OverrideSizeMap;
1189     gExtraBlockOffsetMap->set(this, blockOffest);
1190 }
1191
1192 void RenderBox::clearExtraInlineAndBlockOffests()
1193 {
1194     if (gExtraInlineOffsetMap)
1195         gExtraInlineOffsetMap->remove(this);
1196     if (gExtraBlockOffsetMap)
1197         gExtraBlockOffsetMap->remove(this);
1198 }
1199 #endif // ENABLE(CSS_GRID_LAYOUT)
1200
1201 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1202 {
1203     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1204     if (style().boxSizing() == CONTENT_BOX)
1205         return width + bordersPlusPadding;
1206     return std::max(width, bordersPlusPadding);
1207 }
1208
1209 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1210 {
1211     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1212     if (style().boxSizing() == CONTENT_BOX)
1213         return height + bordersPlusPadding;
1214     return std::max(height, bordersPlusPadding);
1215 }
1216
1217 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1218 {
1219     if (style().boxSizing() == BORDER_BOX)
1220         width -= borderAndPaddingLogicalWidth();
1221     return std::max<LayoutUnit>(0, width);
1222 }
1223
1224 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(Optional<LayoutUnit> height) const
1225 {
1226     if (!height)
1227         return 0;
1228     LayoutUnit result = height.value();
1229     if (style().boxSizing() == BORDER_BOX)
1230         result -= borderAndPaddingLogicalHeight();
1231     return std::max(LayoutUnit(), result);
1232 }
1233
1234 // Hit Testing
1235 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1236 {
1237     LayoutPoint adjustedLocation = accumulatedOffset + location();
1238
1239     // Check kids first.
1240     for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1241         if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1242             updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1243             return true;
1244         }
1245     }
1246
1247     RenderFlowThread* flowThread = flowThreadContainingBlock();
1248     RenderRegion* regionToUse = flowThread ? downcast<RenderNamedFlowFragment>(flowThread->currentRegion()) : nullptr;
1249
1250     // If the box is not contained by this region there's no point in going further.
1251     if (regionToUse && !flowThread->objectShouldFragmentInFlowRegion(this, regionToUse))
1252         return false;
1253
1254     // Check our bounds next. For this purpose always assume that we can only be hit in the
1255     // foreground phase (which is true for replaced elements like images).
1256     LayoutRect boundsRect = borderBoxRectInRegion(regionToUse);
1257     boundsRect.moveBy(adjustedLocation);
1258     if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1259         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1260         if (!result.addNodeToRectBasedTestResult(element(), request, locationInContainer, boundsRect))
1261             return true;
1262     }
1263
1264     return false;
1265 }
1266
1267 // --------------------- painting stuff -------------------------------
1268
1269 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1270 {
1271     if (paintInfo.skipRootBackground())
1272         return;
1273
1274     auto& rootBackgroundRenderer = rendererForRootBackground();
1275     
1276     const FillLayer* bgLayer = rootBackgroundRenderer.style().backgroundLayers();
1277     Color bgColor = rootBackgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1278
1279     paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(), BackgroundBleedNone, CompositeSourceOver, &rootBackgroundRenderer);
1280 }
1281
1282 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext& context) const
1283 {
1284     if (context.paintingDisabled())
1285         return BackgroundBleedNone;
1286
1287     const RenderStyle& style = this->style();
1288
1289     if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1290         return BackgroundBleedNone;
1291
1292     AffineTransform ctm = context.getCTM();
1293     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1294
1295     // Because RoundedRect uses IntRect internally the inset applied by the 
1296     // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1297     // layout coordinate, even with subpixel layout enabled. To take that into
1298     // account, we clamp the contextScaling to 1.0 for the following test so
1299     // that borderObscuresBackgroundEdge can only return true if the border
1300     // widths are greater than 2 in both layout coordinates and screen
1301     // coordinates.
1302     // This precaution will become obsolete if RoundedRect is ever promoted to
1303     // a sub-pixel representation.
1304     if (contextScaling.width() > 1) 
1305         contextScaling.setWidth(1);
1306     if (contextScaling.height() > 1) 
1307         contextScaling.setHeight(1);
1308
1309     if (borderObscuresBackgroundEdge(contextScaling))
1310         return BackgroundBleedShrinkBackground;
1311     if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1312         return BackgroundBleedBackgroundOverBorder;
1313
1314     return BackgroundBleedUseTransparencyLayer;
1315 }
1316
1317 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1318 {
1319     if (!paintInfo.shouldPaintWithinRoot(*this))
1320         return;
1321
1322     LayoutRect paintRect = borderBoxRectInRegion(currentRenderNamedFlowFragment());
1323     paintRect.moveBy(paintOffset);
1324
1325 #if PLATFORM(IOS)
1326     // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1327     if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1328         int width = std::min(paintRect.width(), paintRect.height());
1329         int height = width;
1330         paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1331     }
1332 #endif
1333     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context());
1334
1335     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1336     // custom shadows of their own.
1337     if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1338         paintBoxShadow(paintInfo, paintRect, style(), Normal);
1339
1340     GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
1341     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1342         // To avoid the background color bleeding out behind the border, we'll render background and border
1343         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1344         // beginning the layer).
1345         stateSaver.save();
1346         paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1347         paintInfo.context().beginTransparencyLayer(1);
1348     }
1349
1350     // If we have a native theme appearance, paint that before painting our background.
1351     // The theme will tell us whether or not we should also paint the CSS background.
1352     ControlStates* controlStates = nullptr;
1353     bool borderOrBackgroundPaintingIsNeeded = true;
1354     if (style().hasAppearance()) {
1355         if (hasControlStatesForRenderer(this))
1356             controlStates = controlStatesForRenderer(this);
1357         else {
1358             controlStates = new ControlStates();
1359             addControlStatesForRenderer(this, controlStates);
1360         }
1361         borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect);
1362         if (controlStates->needsRepaint())
1363             view().scheduleLazyRepaint(*this);
1364     }
1365
1366     if (borderOrBackgroundPaintingIsNeeded) {
1367         if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1368             paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1369
1370         paintBackground(paintInfo, paintRect, bleedAvoidance);
1371
1372         if (style().hasAppearance())
1373             theme().paintDecorations(*this, paintInfo, paintRect);
1374     }
1375     paintBoxShadow(paintInfo, paintRect, style(), Inset);
1376
1377     // The theme will tell us whether or not we should also paint the CSS border.
1378     if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasVisibleBorderDecoration())
1379         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1380
1381     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1382         paintInfo.context().endTransparencyLayer();
1383 }
1384
1385 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1386 {
1387     if (isDocumentElementRenderer()) {
1388         paintRootBoxFillLayers(paintInfo);
1389         return;
1390     }
1391     if (isBody() && skipBodyBackground(this))
1392         return;
1393     if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1394         return;
1395     paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1396 }
1397
1398 bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const
1399 {
1400     ASSERT(hasBackground());
1401     LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1402
1403     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1404     if (backgroundColor.isValid() && backgroundColor.alpha()) {
1405         paintedExtent = backgroundRect;
1406         return true;
1407     }
1408
1409     if (!style().backgroundLayers()->image() || style().backgroundLayers()->next()) {
1410         paintedExtent =  backgroundRect;
1411         return true;
1412     }
1413
1414     BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *style().backgroundLayers(), paintOffset, backgroundRect);
1415     paintedExtent = geometry.destRect();
1416     return !geometry.hasNonLocalGeometry();
1417 }
1418
1419 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1420 {
1421     if (isBody() && skipBodyBackground(this))
1422         return false;
1423
1424     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1425     if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1426         return false;
1427
1428     // If the element has appearance, it might be painted by theme.
1429     // We cannot be sure if theme paints the background opaque.
1430     // In this case it is safe to not assume opaqueness.
1431     // FIXME: May be ask theme if it paints opaque.
1432     if (style().hasAppearance())
1433         return false;
1434     // FIXME: Check the opaqueness of background images.
1435
1436     if (hasClip() || hasClipPath())
1437         return false;
1438
1439     // FIXME: Use rounded rect if border radius is present.
1440     if (style().hasBorderRadius())
1441         return false;
1442     
1443     // FIXME: The background color clip is defined by the last layer.
1444     if (style().backgroundLayers()->next())
1445         return false;
1446     LayoutRect backgroundRect;
1447     switch (style().backgroundClip()) {
1448     case BorderFillBox:
1449         backgroundRect = borderBoxRect();
1450         break;
1451     case PaddingFillBox:
1452         backgroundRect = paddingBoxRect();
1453         break;
1454     case ContentFillBox:
1455         backgroundRect = contentBoxRect();
1456         break;
1457     default:
1458         break;
1459     }
1460     return backgroundRect.contains(localRect);
1461 }
1462
1463 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1464 {
1465     const RenderStyle& childStyle = childBox.style();
1466     if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1467         return false;
1468     if (childStyle.visibility() != VISIBLE)
1469         return false;
1470 #if ENABLE(CSS_SHAPES)
1471     if (childStyle.shapeOutside())
1472         return false;
1473 #endif
1474     if (!childBox.width() || !childBox.height())
1475         return false;
1476     if (RenderLayer* childLayer = childBox.layer()) {
1477         if (childLayer->isComposited())
1478             return false;
1479         // FIXME: Deal with z-index.
1480         if (!childStyle.hasAutoZIndex())
1481             return false;
1482         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1483             return false;
1484         if (!childBox.scrollPosition().isZero())
1485             return false;
1486     }
1487     return true;
1488 }
1489
1490 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1491 {
1492     if (!maxDepthToTest)
1493         return false;
1494     for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1495         if (!isCandidateForOpaquenessTest(childBox))
1496             continue;
1497         LayoutPoint childLocation = childBox.location();
1498         if (childBox.isRelPositioned())
1499             childLocation.move(childBox.relativePositionOffset());
1500         LayoutRect childLocalRect = localRect;
1501         childLocalRect.moveBy(-childLocation);
1502         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1503             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1504             if (childBox.style().position() == StaticPosition)
1505                 return false;
1506             continue;
1507         }
1508         if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1509             continue;
1510         if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1511             return true;
1512         if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1513             return true;
1514     }
1515     return false;
1516 }
1517
1518 bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
1519 {
1520     // Test to see if the children trivially obscure the background.
1521     // FIXME: This test can be much more comprehensive.
1522     if (!hasBackground())
1523         return false;
1524     // Table and root background painting is special.
1525     if (isTable() || isDocumentElementRenderer())
1526         return false;
1527
1528     LayoutRect backgroundRect;
1529     if (!getBackgroundPaintedExtent(paintOffset, backgroundRect))
1530         return false;
1531     return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1532 }
1533
1534 bool RenderBox::backgroundHasOpaqueTopLayer() const
1535 {
1536     const FillLayer* fillLayer = style().backgroundLayers();
1537     if (!fillLayer || fillLayer->clip() != BorderFillBox)
1538         return false;
1539
1540     // Clipped with local scrolling
1541     if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment)
1542         return false;
1543
1544     if (fillLayer->hasOpaqueImage(*this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style().effectiveZoom()))
1545         return true;
1546
1547     // If there is only one layer and no image, check whether the background color is opaque
1548     if (!fillLayer->next() && !fillLayer->hasImage()) {
1549         Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1550         if (bgColor.isValid() && bgColor.alpha() == 255)
1551             return true;
1552     }
1553
1554     return false;
1555 }
1556
1557 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1558 {
1559     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context().paintingDisabled())
1560         return;
1561
1562     LayoutRect paintRect = LayoutRect(paintOffset, size());
1563     paintMaskImages(paintInfo, paintRect);
1564 }
1565
1566 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1567 {
1568     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context().paintingDisabled())
1569         return;
1570
1571     LayoutRect paintRect = LayoutRect(paintOffset, size());
1572     paintInfo.context().fillRect(snappedIntRect(paintRect), Color::black);
1573 }
1574
1575 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1576 {
1577     // Figure out if we need to push a transparency layer to render our mask.
1578     bool pushTransparencyLayer = false;
1579     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1580     bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1581     CompositeOperator compositeOp = CompositeSourceOver;
1582
1583     bool allMaskImagesLoaded = true;
1584     
1585     if (!compositedMask || flattenCompositingLayers) {
1586         pushTransparencyLayer = true;
1587         StyleImage* maskBoxImage = style().maskBoxImage().image();
1588         const FillLayer* maskLayers = style().maskLayers();
1589
1590         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1591         if (maskBoxImage)
1592             allMaskImagesLoaded &= maskBoxImage->isLoaded();
1593
1594         if (maskLayers)
1595             allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1596
1597         paintInfo.context().setCompositeOperation(CompositeDestinationIn);
1598         paintInfo.context().beginTransparencyLayer(1);
1599         compositeOp = CompositeSourceOver;
1600     }
1601
1602     if (allMaskImagesLoaded) {
1603         paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1604         paintNinePieceImage(paintInfo.context(), paintRect, style(), style().maskBoxImage(), compositeOp);
1605     }
1606     
1607     if (pushTransparencyLayer)
1608         paintInfo.context().endTransparencyLayer();
1609 }
1610
1611 LayoutRect RenderBox::maskClipRect(const LayoutPoint& paintOffset)
1612 {
1613     const NinePieceImage& maskBoxImage = style().maskBoxImage();
1614     if (maskBoxImage.image()) {
1615         LayoutRect borderImageRect = borderBoxRect();
1616         
1617         // Apply outsets to the border box.
1618         borderImageRect.expand(style().maskBoxImageOutsets());
1619         return borderImageRect;
1620     }
1621     
1622     LayoutRect result;
1623     LayoutRect borderBox = borderBoxRect();
1624     for (const FillLayer* maskLayer = style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1625         if (maskLayer->image()) {
1626             // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1627             BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *maskLayer, paintOffset, borderBox);
1628             result.unite(geometry.destRect());
1629         }
1630     }
1631     return result;
1632 }
1633
1634 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1635     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1636 {
1637     Vector<const FillLayer*, 8> layers;
1638     const FillLayer* curLayer = fillLayer;
1639     bool shouldDrawBackgroundInSeparateBuffer = false;
1640     while (curLayer) {
1641         layers.append(curLayer);
1642         // Stop traversal when an opaque layer is encountered.
1643         // FIXME : It would be possible for the following occlusion culling test to be more aggressive 
1644         // on layers with no repeat by testing whether the image covers the layout rect.
1645         // Testing that here would imply duplicating a lot of calculations that are currently done in
1646         // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1647         // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1648         // and pass it down.
1649
1650         if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
1651             shouldDrawBackgroundInSeparateBuffer = true;
1652
1653         // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1654         if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(*this) && curLayer->image()->canRender(this, style().effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
1655             break;
1656         curLayer = curLayer->next();
1657     }
1658
1659     GraphicsContext& context = paintInfo.context();
1660     BaseBackgroundColorUsage baseBgColorUsage = BaseBackgroundColorUse;
1661
1662     if (shouldDrawBackgroundInSeparateBuffer) {
1663         paintFillLayer(paintInfo, c, *layers.rbegin(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1664         baseBgColorUsage = BaseBackgroundColorSkip;
1665         context.beginTransparencyLayer(1);
1666     }
1667
1668     Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1669     for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1670         paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1671
1672     if (shouldDrawBackgroundInSeparateBuffer)
1673         context.endTransparencyLayer();
1674 }
1675
1676 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1677     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1678 {
1679     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1680 }
1681
1682 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1683 {
1684     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1685         if (curLayer->image() && image == curLayer->image()->data())
1686             return true;
1687     }
1688
1689     return false;
1690 }
1691
1692 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1693 {
1694     if (!parent())
1695         return;
1696
1697     if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1698         (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1699         repaint();
1700         return;
1701     }
1702
1703 #if ENABLE(CSS_SHAPES)
1704     ShapeValue* shapeOutsideValue = style().shapeOutside();
1705     if (!view().frameView().isInRenderTreeLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1706         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1707         markShapeOutsideDependentsForLayout();
1708     }
1709 #endif
1710
1711     bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1712     if (!didFullRepaint)
1713         repaintLayerRectsForImage(image, style().maskLayers(), false);
1714
1715     if (!isComposited())
1716         return;
1717
1718     if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1719         layer()->contentChanged(MaskImageChanged);
1720     if (layersUseImage(image, style().backgroundLayers()))
1721         layer()->contentChanged(BackgroundImageChanged);
1722 }
1723
1724 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1725 {
1726     LayoutRect rendererRect;
1727     RenderBox* layerRenderer = nullptr;
1728
1729     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1730         if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) {
1731             // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1732             bool drawingRootBackground = drawingBackground && (isDocumentElementRenderer() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1733             if (!layerRenderer) {
1734                 if (drawingRootBackground) {
1735                     layerRenderer = &view();
1736
1737                     LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1738                     LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1739
1740                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1741                         -layerRenderer->marginTop(),
1742                         std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1743                         std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1744                 } else {
1745                     layerRenderer = this;
1746                     rendererRect = borderBoxRect();
1747                 }
1748             }
1749             // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping)
1750             BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *curLayer, LayoutPoint(), rendererRect);
1751             if (geometry.hasNonLocalGeometry()) {
1752                 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1753                 // in order to get the right destRect, just repaint the entire renderer.
1754                 layerRenderer->repaint();
1755                 return true;
1756             }
1757             
1758             LayoutRect rectToRepaint = geometry.destRect();
1759             bool shouldClipToLayer = true;
1760
1761             // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1762             // extendedBackground. We should only extend the rect if it is already extending the full width or height
1763             // of the rendererRect.
1764             if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1765                 shouldClipToLayer = false;
1766                 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1767                 if (rectToRepaint.width() == rendererRect.width()) {
1768                     rectToRepaint.move(extendedBackgroundRect.x(), 0);
1769                     rectToRepaint.setWidth(extendedBackgroundRect.width());
1770                 }
1771                 if (rectToRepaint.height() == rendererRect.height()) {
1772                     rectToRepaint.move(0, extendedBackgroundRect.y());
1773                     rectToRepaint.setHeight(extendedBackgroundRect.height());
1774                 }
1775             }
1776
1777             layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1778             if (geometry.destRect() == rendererRect)
1779                 return true;
1780         }
1781     }
1782     return false;
1783 }
1784
1785 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1786 {
1787     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1788         return false;
1789         
1790     bool isControlClip = hasControlClip();
1791     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1792     
1793     if (!isControlClip && !isOverflowClip)
1794         return false;
1795     
1796     if (paintInfo.phase == PaintPhaseOutline)
1797         paintInfo.phase = PaintPhaseChildOutlines;
1798     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1799         paintInfo.phase = PaintPhaseBlockBackground;
1800         paintObject(paintInfo, accumulatedOffset);
1801         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1802     }
1803     float deviceScaleFactor = document().deviceScaleFactor();
1804     FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1805     paintInfo.context().save();
1806     if (style().hasBorderRadius())
1807         paintInfo.context().clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1808     paintInfo.context().clip(clipRect);
1809     return true;
1810 }
1811
1812 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1813 {
1814     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1815
1816     paintInfo.context().restore();
1817     if (originalPhase == PaintPhaseOutline) {
1818         paintInfo.phase = PaintPhaseSelfOutline;
1819         paintObject(paintInfo, accumulatedOffset);
1820         paintInfo.phase = originalPhase;
1821     } else if (originalPhase == PaintPhaseChildBlockBackground)
1822         paintInfo.phase = originalPhase;
1823 }
1824
1825 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1826 {
1827     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1828     // here.
1829     LayoutRect clipRect = borderBoxRectInRegion(region);
1830     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1831     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1832
1833     // Subtract out scrollbars if we have them.
1834     if (layer()) {
1835         if (shouldPlaceBlockDirectionScrollbarOnLeft())
1836             clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1837         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1838     }
1839
1840     return clipRect;
1841 }
1842
1843 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1844 {
1845     LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1846     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1847
1848     if (!style().clipLeft().isAuto()) {
1849         LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1850         clipRect.move(c, 0);
1851         clipRect.contract(c, 0);
1852     }
1853
1854     // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1855     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1856
1857     if (!style().clipRight().isAuto())
1858         clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1859
1860     if (!style().clipTop().isAuto()) {
1861         LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1862         clipRect.move(0, c);
1863         clipRect.contract(0, c);
1864     }
1865
1866     if (!style().clipBottom().isAuto())
1867         clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1868
1869     return clipRect;
1870 }
1871
1872 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock& cb, RenderRegion* region) const
1873 {    
1874     RenderRegion* containingBlockRegion = nullptr;
1875     LayoutUnit logicalTopPosition = logicalTop();
1876     if (region) {
1877         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1878         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1879         containingBlockRegion = cb.clampToStartAndEndRegions(region);
1880     }
1881
1882     LayoutUnit logicalHeight = cb.logicalHeightForChild(*this);
1883     LayoutUnit result = cb.availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd;
1884
1885     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1886     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1887     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1888     // 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
1889     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1890     if (childMarginStart > 0) {
1891         LayoutUnit startContentSide = cb.startOffsetForContent(containingBlockRegion);
1892         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1893         LayoutUnit startOffset = cb.startOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight);
1894         if (startOffset > startContentSideWithMargin)
1895             result += childMarginStart;
1896         else
1897             result += startOffset - startContentSide;
1898     }
1899     
1900     if (childMarginEnd > 0) {
1901         LayoutUnit endContentSide = cb.endOffsetForContent(containingBlockRegion);
1902         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1903         LayoutUnit endOffset = cb.endOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight);
1904         if (endOffset > endContentSideWithMargin)
1905             result += childMarginEnd;
1906         else
1907             result += endOffset - endContentSide;
1908     }
1909
1910     return result;
1911 }
1912
1913 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1914 {
1915 #if ENABLE(CSS_GRID_LAYOUT)
1916     if (hasOverrideContainingBlockLogicalWidth()) {
1917         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
1918             return overrideLogicalWidth.value();
1919     }
1920 #endif
1921
1922     if (RenderBlock* cb = containingBlock())
1923         return cb->availableLogicalWidth();
1924     return LayoutUnit();
1925 }
1926
1927 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1928 {
1929 #if ENABLE(CSS_GRID_LAYOUT)
1930     if (hasOverrideContainingBlockLogicalHeight()) {
1931         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1932             return overrideLogicalHeight.value();
1933     }
1934 #endif
1935
1936     if (RenderBlock* cb = containingBlock())
1937         return cb->availableLogicalHeight(heightType);
1938     return LayoutUnit();
1939 }
1940
1941 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1942 {
1943     if (!region)
1944         return containingBlockLogicalWidthForContent();
1945
1946     RenderBlock* cb = containingBlock();
1947     RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1948     // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1949     // If it should, the following line should call containingBlockLogicalWidthForContent.
1950     LayoutUnit result = cb->availableLogicalWidth();
1951     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1952     if (!boxInfo)
1953         return result;
1954     return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1955 }
1956
1957 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1958 {
1959     RenderBlock* cb = containingBlock();
1960     RenderRegion* containingBlockRegion = nullptr;
1961     LayoutUnit logicalTopPosition = logicalTop();
1962     if (region) {
1963         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1964         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1965         containingBlockRegion = cb->clampToStartAndEndRegions(region);
1966     }
1967     return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1968 }
1969
1970 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1971 {
1972 #if ENABLE(CSS_GRID_LAYOUT)
1973     if (hasOverrideContainingBlockLogicalHeight()) {
1974         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1975             return overrideLogicalHeight.value();
1976     }
1977 #endif
1978
1979     RenderBlock* cb = containingBlock();
1980     if (cb->hasOverrideLogicalContentHeight())
1981         return cb->overrideLogicalContentHeight();
1982
1983     const RenderStyle& containingBlockStyle = cb->style();
1984     Length logicalHeightLength = containingBlockStyle.logicalHeight();
1985
1986     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1987     if (!logicalHeightLength.isFixed()) {
1988         LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1989         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1990         return std::min(fillAvailableExtent, fillFallbackExtent);
1991     }
1992
1993     // Use the content box logical height as specified by the style.
1994     return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value()));
1995 }
1996
1997 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1998 {
1999     if (repaintContainer == this)
2000         return;
2001
2002     if (view().layoutStateEnabled() && !repaintContainer) {
2003         LayoutState* layoutState = view().layoutState();
2004         LayoutSize offset = layoutState->m_paintOffset + locationOffset();
2005         if (style().hasInFlowPosition() && layer())
2006             offset += layer()->offsetForInFlowPosition();
2007         transformState.move(offset);
2008         return;
2009     }
2010
2011     bool containerSkipped;
2012     RenderElement* container = this->container(repaintContainer, containerSkipped);
2013     if (!container)
2014         return;
2015
2016     bool isFixedPos = style().position() == FixedPosition;
2017     // If this box has a transform, it acts as a fixed position container for fixed descendants,
2018     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2019     if (hasTransform() && !isFixedPos)
2020         mode &= ~IsFixed;
2021     else if (isFixedPos)
2022         mode |= IsFixed;
2023
2024     if (wasFixed)
2025         *wasFixed = mode & IsFixed;
2026     
2027     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
2028     
2029     bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
2030     if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
2031         TransformationMatrix t;
2032         getTransformFromContainer(container, containerOffset, t);
2033         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2034     } else
2035         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2036
2037     if (containerSkipped) {
2038         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
2039         // to just subtract the delta between the repaintContainer and o.
2040         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
2041         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2042         return;
2043     }
2044
2045     mode &= ~ApplyContainerFlip;
2046
2047     // For fixed positioned elements inside out-of-flow named flows, we do not want to
2048     // map their position further to regions based on their coordinates inside the named flows.
2049     if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
2050         container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2051     else
2052         container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed);
2053 }
2054
2055 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2056 {
2057     ASSERT(ancestorToStopAt != this);
2058
2059     bool ancestorSkipped;
2060     RenderElement* container = this->container(ancestorToStopAt, ancestorSkipped);
2061     if (!container)
2062         return nullptr;
2063
2064     bool isFixedPos = style().position() == FixedPosition;
2065     LayoutSize adjustmentForSkippedAncestor;
2066     if (ancestorSkipped) {
2067         // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
2068         // to just subtract the delta between the ancestor and container.
2069         adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2070     }
2071
2072     bool offsetDependsOnPoint = false;
2073     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2074
2075     bool preserve3D = container->style().preserves3D() || style().preserves3D();
2076     if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2077         TransformationMatrix t;
2078         getTransformFromContainer(container, containerOffset, t);
2079         t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2080         
2081         geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2082     } else {
2083         containerOffset += adjustmentForSkippedAncestor;
2084         geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2085     }
2086     
2087     return ancestorSkipped ? ancestorToStopAt : container;
2088 }
2089
2090 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2091 {
2092     bool isFixedPos = style().position() == FixedPosition;
2093     if (hasTransform() && !isFixedPos) {
2094         // If this box has a transform, it acts as a fixed position container for fixed descendants,
2095         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2096         mode &= ~IsFixed;
2097     } else if (isFixedPos)
2098         mode |= IsFixed;
2099
2100     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2101 }
2102
2103 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2104 {
2105     // A region "has" boxes inside it without being their container. 
2106     ASSERT(&renderer == container() || is<RenderRegion>(renderer));
2107
2108     LayoutSize offset;    
2109     if (isInFlowPositioned())
2110         offset += offsetForInFlowPosition();
2111
2112     if (!isInline() || isReplaced())
2113         offset += topLeftLocationOffset();
2114
2115     if (is<RenderBox>(renderer))
2116         offset -= toLayoutSize(downcast<RenderBox>(renderer).scrollPosition());
2117
2118     if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2119         offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2120
2121     if (offsetDependsOnPoint)
2122         *offsetDependsOnPoint |= is<RenderFlowThread>(renderer);
2123
2124     return offset;
2125 }
2126
2127 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2128 {
2129     return std::make_unique<InlineElementBox>(*this);
2130 }
2131
2132 void RenderBox::dirtyLineBoxes(bool fullLayout)
2133 {
2134     if (m_inlineBoxWrapper) {
2135         if (fullLayout) {
2136             delete m_inlineBoxWrapper;
2137             m_inlineBoxWrapper = nullptr;
2138         } else
2139             m_inlineBoxWrapper->dirtyLineBoxes();
2140     }
2141 }
2142
2143 void RenderBox::positionLineBox(InlineElementBox& box)
2144 {
2145     if (isOutOfFlowPositioned()) {
2146         // Cache the x position only if we were an INLINE type originally.
2147         bool wasInline = style().isOriginalDisplayInlineType();
2148         if (wasInline) {
2149             // The value is cached in the xPos of the box.  We only need this value if
2150             // our object was inline originally, since otherwise it would have ended up underneath
2151             // the inlines.
2152             RootInlineBox& rootBox = box.root();
2153             rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2154             if (style().hasStaticInlinePosition(box.isHorizontal()))
2155                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2156         } else {
2157             // Our object was a block originally, so we make our normal flow position be
2158             // just below the line box (as though all the inlines that came before us got
2159             // wrapped in an anonymous block, which is what would have happened had we been
2160             // in flow).  This value was cached in the y() of the box.
2161             layer()->setStaticBlockPosition(box.logicalTop());
2162             if (style().hasStaticBlockPosition(box.isHorizontal()))
2163                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2164         }
2165         return;
2166     }
2167
2168     if (isReplaced()) {
2169         setLocation(LayoutPoint(box.topLeft()));
2170         setInlineBoxWrapper(&box);
2171     }
2172 }
2173
2174 void RenderBox::deleteLineBoxWrapper()
2175 {
2176     if (m_inlineBoxWrapper) {
2177         if (!documentBeingDestroyed())
2178             m_inlineBoxWrapper->removeFromParent();
2179         delete m_inlineBoxWrapper;
2180         m_inlineBoxWrapper = nullptr;
2181     }
2182 }
2183
2184 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2185 {
2186     if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2187         return LayoutRect();
2188     LayoutRect r = visualOverflowRect();
2189     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2190     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2191     r.move(view().layoutDelta());
2192     return computeRectForRepaint(r, repaintContainer);
2193 }
2194
2195 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2196 {
2197 #if PLATFORM(IOS)
2198     if (!repaintContainer || repaintContainer != containerBox)
2199         return true;
2200
2201     return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2202 #else
2203     UNUSED_PARAM(repaintContainer);
2204     UNUSED_PARAM(containerBox);
2205     return true;
2206 #endif
2207 }
2208
2209 LayoutRect RenderBox::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, bool fixed) const
2210 {
2211     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2212     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2213     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2214     // properly even during layout, since the rect remains flipped all the way until the end.
2215     //
2216     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2217     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2218     // physical coordinate space of the repaintContainer.
2219     LayoutRect adjustedRect = rect;
2220     const RenderStyle& styleToUse = style();
2221     // LayoutState is only valid for root-relative, non-fixed position repainting
2222     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2223         LayoutState* layoutState = view().layoutState();
2224
2225         if (layer() && layer()->transform())
2226             adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2227
2228         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2229         if (styleToUse.hasInFlowPosition() && layer())
2230             adjustedRect.move(layer()->offsetForInFlowPosition());
2231
2232         adjustedRect.moveBy(location());
2233         adjustedRect.move(layoutState->m_paintOffset);
2234         if (layoutState->m_clipped)
2235             adjustedRect.intersect(layoutState->m_clipRect);
2236         return adjustedRect;
2237     }
2238
2239     if (hasReflection())
2240         adjustedRect.unite(reflectedRect(adjustedRect));
2241
2242     if (repaintContainer == this) {
2243         if (repaintContainer->style().isFlippedBlocksWritingMode())
2244             flipForWritingMode(adjustedRect);
2245         return adjustedRect;
2246     }
2247
2248     bool containerSkipped;
2249     auto* renderer = container(repaintContainer, containerSkipped);
2250     if (!renderer)
2251         return adjustedRect;
2252     
2253     EPosition position = styleToUse.position();
2254
2255     // This code isn't necessary for in-flow RenderFlowThreads.
2256     // Don't add the location of the region in the flow thread for absolute positioned
2257     // elements because their absolute position already pushes them down through
2258     // the regions so adding this here and then adding the topLeft again would cause
2259     // us to add the height twice.
2260     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2261     // will already contain the portion rect of the region.
2262     if (renderer->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2263         RenderRegion* firstRegion = nullptr;
2264         RenderRegion* lastRegion = nullptr;
2265         if (downcast<RenderFlowThread>(*renderer).getRegionRangeForBox(this, firstRegion, lastRegion))
2266             adjustedRect.moveBy(firstRegion->flowThreadPortionRect().location());
2267     }
2268
2269     if (isWritingModeRoot() && !isOutOfFlowPositioned())
2270         flipForWritingMode(adjustedRect);
2271
2272     LayoutSize locationOffset = this->locationOffset();
2273     // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2274     if (isRenderReplaced() && isWidget()) {
2275         LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2276         adjustedRect.expand(locationOffset - flooredLocationOffset);
2277         locationOffset = flooredLocationOffset;
2278     }
2279     LayoutPoint topLeft = adjustedRect.location();
2280     topLeft.move(locationOffset);
2281
2282     // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2283     // in the parent's coordinate space that encloses us.
2284     if (hasLayer() && layer()->transform()) {
2285         fixed = position == FixedPosition;
2286         adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2287         topLeft = adjustedRect.location();
2288         topLeft.move(locationOffset);
2289     } else if (position == FixedPosition)
2290         fixed = true;
2291
2292     if (position == AbsolutePosition && renderer->isInFlowPositioned() && is<RenderInline>(*renderer))
2293         topLeft += downcast<RenderInline>(*renderer).offsetForInFlowPositionedInline(this);
2294     else if (styleToUse.hasInFlowPosition() && layer()) {
2295         // Apply the relative position offset when invalidating a rectangle.  The layer
2296         // is translated, but the render box isn't, so we need to do this to get the
2297         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2298         // flag on the RenderObject has been cleared, so use the one on the style().
2299         topLeft += layer()->offsetForInFlowPosition();
2300     }
2301
2302     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2303     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2304     adjustedRect.setLocation(topLeft);
2305     if (renderer->hasOverflowClip()) {
2306         RenderBox& containerBox = downcast<RenderBox>(*renderer);
2307         if (shouldApplyContainersClipAndOffset(repaintContainer, &containerBox)) {
2308             containerBox.applyCachedClipAndScrollOffsetForRepaint(adjustedRect);
2309             if (adjustedRect.isEmpty())
2310                 return adjustedRect;
2311         }
2312     }
2313
2314     if (containerSkipped) {
2315         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2316         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*renderer);
2317         adjustedRect.move(-containerOffset);
2318         return adjustedRect;
2319     }
2320     return renderer->computeRectForRepaint(adjustedRect, repaintContainer, fixed);
2321 }
2322
2323 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2324 {
2325     if (oldRect.location() != m_frameRect.location()) {
2326         LayoutRect newRect = m_frameRect;
2327         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2328         // since the object may not have gotten a layout.
2329         m_frameRect = oldRect;
2330         repaint();
2331         repaintOverhangingFloats(true);
2332         m_frameRect = newRect;
2333         repaint();
2334         repaintOverhangingFloats(true);
2335     }
2336 }
2337
2338 void RenderBox::repaintOverhangingFloats(bool)
2339 {
2340 }
2341
2342 void RenderBox::updateLogicalWidth()
2343 {
2344     LogicalExtentComputedValues computedValues;
2345     computeLogicalWidthInRegion(computedValues);
2346
2347     setLogicalWidth(computedValues.m_extent);
2348     setLogicalLeft(computedValues.m_position);
2349     setMarginStart(computedValues.m_margins.m_start);
2350     setMarginEnd(computedValues.m_margins.m_end);
2351 }
2352
2353 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2354 {
2355     computedValues.m_extent = logicalWidth();
2356     computedValues.m_position = logicalLeft();
2357     computedValues.m_margins.m_start = marginStart();
2358     computedValues.m_margins.m_end = marginEnd();
2359
2360     if (isOutOfFlowPositioned()) {
2361         // FIXME: This calculation is not patched for block-flow yet.
2362         // https://bugs.webkit.org/show_bug.cgi?id=46500
2363         computePositionedLogicalWidth(computedValues, region);
2364         return;
2365     }
2366
2367     // If layout is limited to a subtree, the subtree root's logical width does not change.
2368     if (element() && !view().frameView().layoutPending() && view().frameView().layoutRoot() == this)
2369         return;
2370
2371     // The parent box is flexing us, so it has increased or decreased our
2372     // width.  Use the width from the style context.
2373     // FIXME: Account for block-flow in flexible boxes.
2374     // https://bugs.webkit.org/show_bug.cgi?id=46418
2375     if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()))) {
2376         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2377         return;
2378     }
2379
2380     // FIXME: Account for block-flow in flexible boxes.
2381     // https://bugs.webkit.org/show_bug.cgi?id=46418
2382     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2383     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2384     // FIXME: Stretching is the only reason why we don't want the box to be treated as a replaced element, so we could perhaps
2385     // refactor all this logic, not only for flex and grid since alignment is intended to be applied to any block.
2386     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2387 #if ENABLE(CSS_GRID_LAYOUT)
2388     treatAsReplaced = treatAsReplaced && (!isGridItem() || !hasStretchedLogicalWidth());
2389 #endif
2390
2391     const RenderStyle& styleToUse = style();
2392     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2393
2394     RenderBlock& cb = *containingBlock();
2395     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2396     bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2397
2398     if (isInline() && !isInlineBlockOrInlineTable()) {
2399         // just calculate margins
2400         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2401         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2402         if (treatAsReplaced)
2403             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2404         return;
2405     }
2406
2407     // Width calculations
2408     if (treatAsReplaced) {
2409         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2410 #if ENABLE(CSS_GRID_LAYOUT)
2411     } else if (parent()->isRenderGrid() && style().logicalWidth().isAuto() && style().logicalMinWidth().isAuto() && style().overflowX() == OVISIBLE && containerLogicalWidth < minPreferredLogicalWidth()) {
2412         // TODO (lajava) Move this logic to the LayoutGrid class.
2413         // Implied minimum size of Grid items.
2414         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(minPreferredLogicalWidth(), containerLogicalWidth, cb);
2415 #endif
2416     } else {
2417         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2418         if (hasPerpendicularContainingBlock)
2419             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2420         LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2421         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2422     }
2423
2424     // Margin calculations.
2425     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2426         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2427         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2428     } else {
2429         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2430         if (avoidsFloats() && cb.containsFloats())
2431             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2432         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2433         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2434             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2435             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2436     }
2437     
2438     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2439         && !isFloating() && !isInline() && !cb.isFlexibleBoxIncludingDeprecated()
2440 #if ENABLE(CSS_GRID_LAYOUT)
2441         && !cb.isRenderGrid()
2442 #endif
2443         ) {
2444         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb.marginStartForChild(*this);
2445         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2446         if (hasInvertedDirection)
2447             computedValues.m_margins.m_start = newMargin;
2448         else
2449             computedValues.m_margins.m_end = newMargin;
2450     }
2451 }
2452
2453 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2454 {
2455     LayoutUnit marginStart = 0;
2456     LayoutUnit marginEnd = 0;
2457     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2458 }
2459
2460 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2461 {
2462     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2463     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2464     return availableLogicalWidth - marginStart - marginEnd;
2465 }
2466
2467 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2468 {
2469     if (logicalWidthLength.type() == FillAvailable)
2470         return fillAvailableMeasure(availableLogicalWidth);
2471
2472     LayoutUnit minLogicalWidth = 0;
2473     LayoutUnit maxLogicalWidth = 0;
2474     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2475
2476     if (logicalWidthLength.type() == MinContent)
2477         return minLogicalWidth + borderAndPadding;
2478
2479     if (logicalWidthLength.type() == MaxContent)
2480         return maxLogicalWidth + borderAndPadding;
2481
2482     if (logicalWidthLength.type() == FitContent) {
2483         minLogicalWidth += borderAndPadding;
2484         maxLogicalWidth += borderAndPadding;
2485         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2486     }
2487
2488     ASSERT_NOT_REACHED();
2489     return 0;
2490 }
2491
2492 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2493     const RenderBlock& cb, RenderRegion* region) const
2494 {
2495     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2496     if (widthType == MinSize && logicalWidth.isAuto())
2497         return adjustBorderBoxLogicalWidthForBoxSizing(0);
2498
2499     if (!logicalWidth.isIntrinsicOrAuto()) {
2500         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2501         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2502     }
2503
2504     if (logicalWidth.isIntrinsic())
2505         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2506
2507     LayoutUnit marginStart = 0;
2508     LayoutUnit marginEnd = 0;
2509     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2510
2511     if (shrinkToAvoidFloats() && cb.containsFloats())
2512         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2513
2514     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2515         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2516     return logicalWidthResult;
2517 }
2518
2519 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2520 {
2521     auto parent = flexitem.parent();
2522     return flexitem.style().resolvedAlignSelf(parent->style(), ItemPositionStretch).position() == ItemPositionStretch;
2523 }
2524
2525 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2526 {
2527     auto parent = flexitem.parent();
2528     if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2529         return true;
2530
2531     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2532     if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2533         return true;
2534     return false;
2535 }
2536
2537 // FIXME: Can/Should we move this inside specific layout classes (flex. grid)? Can we refactor columnFlexItemHasStretchAlignment logic?
2538 bool RenderBox::hasStretchedLogicalWidth() const
2539 {
2540     auto& style = this->style();
2541     if (!style.logicalWidth().isAuto() || style.marginStart().isAuto() || style.marginEnd().isAuto())
2542         return false;
2543     RenderBlock* containingBlock = this->containingBlock();
2544     if (!containingBlock) {
2545         // We are evaluating align-self/justify-self, which default to 'normal' for the root element.
2546         // The 'normal' value behaves like 'start' except for Flexbox Items, which obviously should have a container.
2547         return false;
2548     }
2549     if (containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2550         return style.resolvedAlignSelf(containingBlock->style(), ItemPositionStretch).position() == ItemPositionStretch;
2551     return style.resolvedJustifySelf(containingBlock->style(), ItemPositionStretch).position() == ItemPositionStretch;
2552 }
2553
2554 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2555 {
2556     // Anonymous inline blocks always fill the width of their containing block.
2557     if (isAnonymousInlineBlock())
2558         return false;
2559
2560     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2561     // but they allow text to sit on the same line as the marquee.
2562     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2563         return true;
2564
2565 #if ENABLE(CSS_GRID_LAYOUT)
2566     if (isGridItem())
2567         return !hasStretchedLogicalWidth();
2568 #endif
2569
2570     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2571     // min-width and width.  max-width is only clamped if it is also intrinsic.
2572     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2573     if (logicalWidth.type() == Intrinsic)
2574         return true;
2575
2576     // Children of a horizontal marquee do not fill the container by default.
2577     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2578     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2579     // block-flow (as well as how marquee overflow should relate to block flow).
2580     // https://bugs.webkit.org/show_bug.cgi?id=46472
2581     if (parent()->isHTMLMarquee()) {
2582         EMarqueeDirection dir = parent()->style().marqueeDirection();
2583         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2584             return true;
2585     }
2586
2587     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2588     // In the case of columns that have a stretch alignment, we layout at the stretched size
2589     // to avoid an extra layout when applying alignment.
2590     if (parent()->isFlexibleBox()) {
2591         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2592         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2593             return true;
2594         if (!flexItemHasStretchAlignment(*this))
2595             return true;
2596     }
2597
2598     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2599     // that don't stretch their kids lay out their children at their intrinsic widths.
2600     // FIXME: Think about block-flow here.
2601     // https://bugs.webkit.org/show_bug.cgi?id=46473
2602     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2603         return true;
2604
2605     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2606     // stretching column flexbox.
2607     // FIXME: Think about block-flow here.
2608     // https://bugs.webkit.org/show_bug.cgi?id=46473
2609     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2610         return true;
2611
2612     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2613         return true;
2614
2615     return false;
2616 }
2617
2618 void RenderBox::computeInlineDirectionMargins(const RenderBlock& containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2619 {
2620     const RenderStyle& containingBlockStyle = containingBlock.style();
2621     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2622     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2623
2624     if (isFloating() || isInline()) {
2625         // Inline blocks/tables and floats don't have their margins increased.
2626         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2627         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2628         return;
2629     }
2630
2631     // Case One: The object is being centered in the containing block's available logical width.
2632     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2633         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock.style().textAlign() == WEBKIT_CENTER)) {
2634         // Other browsers center the margin box for align=center elements so we match them here.
2635         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2636         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2637         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2638         marginStart = centeredMarginBoxStart + marginStartWidth;
2639         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2640         return;
2641     } 
2642     
2643     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2644     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2645         marginStart = valueForLength(marginStartLength, containerWidth);
2646         marginEnd = containerWidth - childWidth - marginStart;
2647         return;
2648     } 
2649     
2650     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2651     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2652         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2653     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2654         marginEnd = valueForLength(marginEndLength, containerWidth);
2655         marginStart = containerWidth - childWidth - marginEnd;
2656         return;
2657     } 
2658     
2659     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2660     // auto margins will just turn into 0.
2661     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2662     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2663 }
2664
2665 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2666 {
2667     // Make sure nobody is trying to call this with a null region.
2668     if (!region)
2669         return nullptr;
2670
2671     // If we have computed our width in this region already, it will be cached, and we can
2672     // just return it.
2673     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2674     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2675         return boxInfo;
2676
2677     // No cached value was found, so we have to compute our insets in this region.
2678     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2679     // support to cover all boxes.
2680     RenderFlowThread* flowThread = flowThreadContainingBlock();
2681     if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2682         return nullptr;
2683
2684     LogicalExtentComputedValues computedValues;
2685     computeLogicalWidthInRegion(computedValues, region);
2686
2687     // Now determine the insets based off where this object is supposed to be positioned.
2688     RenderBlock& cb = *containingBlock();
2689     RenderRegion* clampedContainingBlockRegion = cb.clampToStartAndEndRegions(region);
2690     RenderBoxRegionInfo* containingBlockInfo = cb.renderBoxRegionInfo(clampedContainingBlockRegion);
2691     LayoutUnit containingBlockLogicalWidth = cb.logicalWidth();
2692     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2693     
2694     LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2695     LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2696     LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2697     LayoutUnit logicalLeftInRegion = computedValues.m_position;
2698     LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2699     LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2700     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2701     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2702     LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2703
2704     LayoutUnit logicalLeftOffset = 0;
2705     
2706     if (!isOutOfFlowPositioned() && avoidsFloats() && cb.containsFloats()) {
2707         LayoutUnit startPositionDelta = cb.computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2708         if (cb.style().isLeftToRightDirection())
2709             logicalLeftDelta += startPositionDelta;
2710         else
2711             logicalRightDelta += startPositionDelta;
2712     }
2713
2714     if (cb.style().isLeftToRightDirection())
2715         logicalLeftOffset += logicalLeftDelta;
2716     else
2717         logicalLeftOffset -= (widthDelta + logicalRightDelta);
2718     
2719     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2720     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2721             || (style().isLeftToRightDirection() && logicalLeftOffset)
2722             || (!style().isLeftToRightDirection() && logicalRightOffset);
2723
2724     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2725     if (cacheFlag == CacheRenderBoxRegionInfo)
2726         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2727     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2728 }
2729
2730 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2731 {
2732     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2733     WritingMode childWritingMode = childStyle->writingMode();
2734     bool shouldFlip = false;
2735     switch (containingBlockStyle.writingMode()) {
2736     case TopToBottomWritingMode:
2737         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2738         break;
2739     case BottomToTopWritingMode:
2740         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2741         break;
2742     case RightToLeftWritingMode:
2743         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2744         break;
2745     case LeftToRightWritingMode:
2746         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2747         break;
2748     }
2749
2750     if (!containingBlockStyle.isLeftToRightDirection())
2751         shouldFlip = !shouldFlip;
2752
2753     return shouldFlip;
2754 }
2755
2756 void RenderBox::updateLogicalHeight()
2757 {
2758     LogicalExtentComputedValues computedValues;
2759     computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2760
2761     setLogicalHeight(computedValues.m_extent);
2762     setLogicalTop(computedValues.m_position);
2763     setMarginBefore(computedValues.m_margins.m_before);
2764     setMarginAfter(computedValues.m_margins.m_after);
2765 }
2766
2767 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2768 {
2769     computedValues.m_extent = logicalHeight;
2770     computedValues.m_position = logicalTop;
2771
2772     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2773     if (isTableCell() || (isInline() && !isReplaced()))
2774         return;
2775
2776     Length h;
2777     if (isOutOfFlowPositioned())
2778         computePositionedLogicalHeight(computedValues);
2779     else {
2780         RenderBlock& cb = *containingBlock();
2781         bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2782     
2783         if (!hasPerpendicularContainingBlock) {
2784             bool shouldFlipBeforeAfter = cb.style().writingMode() != style().writingMode();
2785             computeBlockDirectionMargins(cb,
2786                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2787                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2788         }
2789
2790         // For tables, calculate margins only.
2791         if (isTable()) {
2792             if (hasPerpendicularContainingBlock) {
2793                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2794                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2795                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2796                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2797             }
2798             return;
2799         }
2800
2801         // FIXME: Account for block-flow in flexible boxes.
2802         // https://bugs.webkit.org/show_bug.cgi?id=46418
2803         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2804         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2805         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2806         bool checkMinMaxHeight = false;
2807
2808         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2809         // grab our cached flexible height.
2810         // FIXME: Account for block-flow in flexible boxes.
2811         // https://bugs.webkit.org/show_bug.cgi?id=46418
2812         if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated()
2813 #if ENABLE(CSS_GRID_LAYOUT)
2814             || parent()->isRenderGrid()
2815 #endif
2816         )) {
2817             LayoutUnit contentHeight = overrideLogicalContentHeight();
2818 #if ENABLE(CSS_GRID_LAYOUT)
2819             if (parent()->isRenderGrid() && style().logicalHeight().isAuto() && style().logicalMinHeight().isAuto() && style().overflowX() == OVISIBLE) {
2820                 LayoutUnit intrinsicContentHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2821                 if (auto minContentHeight = computeContentLogicalHeight(MinSize, Length(MinContent), intrinsicContentHeight))
2822                     contentHeight = std::max(contentHeight, constrainContentBoxLogicalHeightByMinMax(minContentHeight.value(), intrinsicContentHeight));
2823             }
2824 #endif
2825             h = Length(contentHeight, Fixed);
2826         } else if (treatAsReplaced)
2827             h = Length(computeReplacedLogicalHeight(), Fixed);
2828         else {
2829             h = style().logicalHeight();
2830             checkMinMaxHeight = true;
2831         }
2832
2833         // Block children of horizontal flexible boxes fill the height of the box.
2834         // FIXME: Account for block-flow in flexible boxes.
2835         // https://bugs.webkit.org/show_bug.cgi?id=46418
2836         if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2837                 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2838             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2839             checkMinMaxHeight = false;
2840         }
2841
2842         LayoutUnit heightResult;
2843         if (checkMinMaxHeight) {
2844             LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2845             heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).valueOr(computedValues.m_extent);
2846             heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2847         } else {
2848             // The only times we don't check min/max height are when a fixed length has
2849             // been given as an override.  Just use that.  The value has already been adjusted
2850             // for box-sizing.
2851             ASSERT(h.isFixed());
2852             heightResult = h.value() + borderAndPaddingLogicalHeight();
2853         }
2854
2855         computedValues.m_extent = heightResult;
2856
2857         if (hasPerpendicularContainingBlock) {
2858             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2859             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2860                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2861                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2862         }
2863     }
2864
2865     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2866     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2867     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2868     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2869     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2870     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2871         && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2872     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2873         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2874         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2875         if (isDocumentElementRenderer())
2876             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2877         else {
2878             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2879             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2880         }
2881     }
2882 }
2883
2884 Optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2885 {
2886     if (Optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2887         return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2888     return Nullopt;
2889 }
2890
2891 Optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2892 {
2893     if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2894         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2895     return Nullopt;
2896 }
2897
2898 Optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, Optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2899 {
2900     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2901     // If that happens, this code will have to change.
2902     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2903         if (!intrinsicContentHeight)
2904             return intrinsicContentHeight;
2905         if (style().boxSizing() == BORDER_BOX)
2906             return intrinsicContentHeight.value() + borderAndPaddingLogicalHeight();
2907         return intrinsicContentHeight;
2908     }
2909     if (logicalHeightLength.isFillAvailable())
2910         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2911     ASSERT_NOT_REACHED();
2912     return LayoutUnit(0);
2913 }
2914
2915 Optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2916 {
2917     if (height.isAuto())
2918         return heightType == MinSize ? Optional<LayoutUnit>(0) : Nullopt;
2919     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2920     // If that happens, this code will have to change.
2921     if (height.isIntrinsic())
2922         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2923     if (height.isFixed())
2924         return LayoutUnit(height.value());
2925     if (height.isPercentOrCalculated())
2926         return computePercentageLogicalHeight(height);
2927     return Nullopt;
2928 }
2929
2930 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox& containingBlock, bool isPerpendicularWritingMode) const
2931 {
2932     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2933     // and percent heights of children should be resolved against the multicol or paged container.
2934     if (containingBlock.isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2935         return true;
2936
2937     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2938     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2939     if (!document().inQuirksMode() && !containingBlock.isAnonymousBlock())
2940         return false;
2941     return !containingBlock.isTableCell() && !containingBlock.isOutOfFlowPositioned() && containingBlock.style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode();
2942 }
2943
2944 static bool tableCellShouldHaveZeroInitialSize(const RenderBlock& block, bool scrollsOverflowY)
2945 {
2946     // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2947     // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2948     // While we can't get all cases right, we can at least detect when the cell has a specified
2949     // height or when the table has a specified height. In these cases we want to initially have
2950     // no size and allow the flexing of the table or the cell to its specified height to cause us
2951     // to grow to fill the space. This could end up being wrong in some cases, but it is
2952     // preferable to the alternative (sizing intrinsically and making the row end up too big).
2953     const RenderTableCell& cell = downcast<RenderTableCell>(block);
2954     return scrollsOverflowY && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto());
2955 }
2956
2957 Optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
2958 {
2959     Optional<LayoutUnit> availableHeight;
2960
2961     bool skippedAutoHeightContainingBlock = false;
2962     RenderBlock* cb = containingBlock();
2963     const RenderBox* containingBlockChild = this;
2964     LayoutUnit rootMarginBorderPaddingHeight = 0;
2965     bool isHorizontal = isHorizontalWritingMode();
2966     while (cb && !is<RenderView>(*cb) && skipContainingBlockForPercentHeightCalculation(*cb, isHorizontal != cb->isHorizontalWritingMode())) {
2967         if (cb->isBody() || cb->isDocumentElementRenderer())
2968             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2969         skippedAutoHeightContainingBlock = true;
2970         containingBlockChild = cb;
2971         cb = cb->containingBlock();
2972         cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2973     }
2974
2975     const RenderStyle& cbstyle = cb->style();
2976
2977     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2978     // explicitly specified that can be used for any percentage computations.
2979     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2980
2981     bool includeBorderPadding = isTable();
2982
2983     if (isHorizontal != cb->isHorizontalWritingMode())
2984         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2985 #if ENABLE(CSS_GRID_LAYOUT)
2986     else if (hasOverrideContainingBlockLogicalHeight())
2987         availableHeight = overrideContainingBlockContentLogicalHeight();
2988 #endif
2989     else if (is<RenderTableCell>(*cb)) {
2990         if (!skippedAutoHeightContainingBlock) {
2991             // Table cells violate what the CSS spec says to do with heights. Basically we
2992             // don't care if the cell specified a height or not. We just always make ourselves
2993             // be a percentage of the cell's current content height.
2994             if (!cb->hasOverrideLogicalContentHeight())
2995                 return tableCellShouldHaveZeroInitialSize(*cb, scrollsOverflowY()) ? Optional<LayoutUnit>() : Nullopt;
2996
2997             availableHeight = cb->overrideLogicalContentHeight();
2998             includeBorderPadding = true;
2999         }
3000     } else if (cbstyle.logicalHeight().isFixed()) {
3001         LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(cbstyle.logicalHeight().value()));
3002         availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), Nullopt));
3003     } else if (cbstyle.logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) {
3004         // We need to recur and compute the percentage height for our containing block.
3005         if (Optional<LayoutUnit> heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight())) {
3006             LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
3007             // We need to adjust for min/max height because this method does not
3008             // handle the min/max of the current block, its caller does. So the
3009             // return value from the recursive call will not have been adjusted
3010             // yet.
3011             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), Nullopt);
3012             availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
3013         }
3014     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
3015         // Don't allow this to affect the block' height() member variable, since this
3016         // can get called while the block is still laying out its kids.
3017         LogicalExtentComputedValues computedValues;
3018         cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
3019         availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
3020     } else if (cb->isRenderView())
3021         availableHeight = view().pageOrViewLogicalHeight();
3022
3023     if (!availableHeight)
3024         return availableHeight;
3025
3026     LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight);
3027     if (includeBorderPadding) {
3028         // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
3029         // It is necessary to use the border-box to match WinIE's broken
3030         // box model. This is essential for sizing inside
3031         // table cells using percentage heights.
3032         result -= borderAndPaddingLogicalHeight();
3033         return std::max<LayoutUnit>(0, result);
3034     }
3035     return result;
3036 }
3037
3038 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
3039 {
3040     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred);
3041 }
3042
3043 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
3044 {
3045     auto& logicalMinWidth = style().logicalMinWidth();
3046     auto& logicalMaxWidth = style().logicalMaxWidth();
3047     bool useLogicalWidthForMinWidth = (shouldComputePreferred == ComputePreferred && logicalMinWidth.isPercentOrCalculated()) || logicalMinWidth.isUndefined();
3048     bool useLogicalWidthForMaxWidth = (shouldComputePreferred == ComputePreferred && logicalMaxWidth.isPercentOrCalculated()) || logicalMaxWidth.isUndefined();
3049     auto minLogicalWidth =  useLogicalWidthForMinWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, logicalMinWidth);
3050     auto maxLogicalWidth =  useLogicalWidthForMaxWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, logicalMaxWidth);
3051     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
3052 }
3053
3054 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const
3055 {
3056     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3057     if (widthType == MinSize && logicalWidth.isAuto())
3058         return adjustContentBoxLogicalWidthForBoxSizing(0);
3059
3060     switch (logicalWidth.type()) {
3061         case Fixed:
3062             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
3063         case MinContent:
3064         case MaxContent: {
3065             // MinContent/MaxContent don't need the availableLogicalWidth argument.
3066             LayoutUnit availableLogicalWidth = 0;
3067             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3068         }
3069         case FitContent:
3070         case FillAvailable:
3071         case Percent: 
3072         case Calculated: {
3073             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
3074             // containing block's block-flow.
3075             // https://bugs.webkit.org/show_bug.cgi?id=46496
3076             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(*container())) : containingBlockLogicalWidthForContent();
3077             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
3078             // FIXME: Handle cases when containing block width is calculated or viewport percent.
3079             // https://bugs.webkit.org/show_bug.cgi?id=91071
3080             if (logicalWidth.isIntrinsic())
3081                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3082             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
3083                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
3084         }
3085         FALLTHROUGH;
3086         case Intrinsic:
3087         case MinIntrinsic:
3088         case Auto:
3089         case Relative:
3090         case Undefined:
3091             return intrinsicLogicalWidth();
3092     }
3093
3094     ASSERT_NOT_REACHED();
3095     return 0;
3096 }
3097
3098 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
3099 {
3100     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight()));
3101 }
3102
3103 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3104 {
3105     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight());
3106     LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight());
3107     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3108 }
3109
3110 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const
3111 {
3112     ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto());
3113     if (heightType == MinSize && logicalHeight.isAuto())
3114         return adjustContentBoxLogicalHeightForBoxSizing(Optional<LayoutUnit>(0));
3115
3116     switch (logicalHeight.type()) {
3117         case Fixed:
3118             return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3119         case Percent:
3120         case Calculated:
3121         {
3122             auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
3123             while (cb && cb->isAnonymous() && !is<RenderView>(*cb)) {
3124                 cb = cb->containingBlock();
3125                 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3126             }
3127
3128             // FIXME: This calculation is not patched for block-flow yet.
3129             // https://bugs.webkit.org/show_bug.cgi?id=46500
3130             if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
3131                 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
3132                 RenderBlock& block = downcast<RenderBlock>(*cb);
3133                 LogicalExtentComputedValues computedValues;
3134                 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3135                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3136                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3137                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3138             }
3139             
3140             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3141             // containing block's block-flow.
3142             // https://bugs.webkit.org/show_bug.cgi?id=46496
3143             LayoutUnit availableHeight;
3144             if (isOutOfFlowPositioned())
3145                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*cb));
3146             else {
3147                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3148                 // It is necessary to use the border-box to match WinIE's broken
3149                 // box model.  This is essential for sizing inside
3150                 // table cells using percentage heights.
3151                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3152                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3153                 while (cb && !is<RenderView>(*cb) && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercentOrCalculated())) {
3154                     if (cb->isTableCell()) {
3155                         // Don't let table cells squeeze percent-height replaced elements
3156                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3157                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3158                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3159                     }
3160                     downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3161                     cb = cb->containingBlock();
3162                 }
3163             }
3164             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3165         }
3166         case MinContent:
3167         case MaxContent:
3168         case FitContent:
3169         case FillAvailable:
3170             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3171         default:
3172             return intrinsicLogicalHeight();
3173     }
3174 }
3175
3176 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3177 {
3178     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), Nullopt);
3179 }
3180
3181 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3182 {
3183     // We need to stop here, since we don't want to increase the height of the table
3184     // artificially.  We're going to rely on this cell getting expanded to some new
3185     // height, and then when we lay out again we'll use the calculation below.
3186     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3187         if (hasOverrideLogicalContentHeight())
3188             return overrideLogicalContentHeight();
3189         return logicalHeight() - borderAndPaddingLogicalHeight();
3190     }
3191
3192     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3193         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3194         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock());
3195         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3196     }
3197
3198     if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, Nullopt))
3199         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3200
3201     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3202     // https://bugs.webkit.org/show_bug.cgi?id=46500
3203     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3204         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3205         LogicalExtentComputedValues computedValues;
3206         block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3207         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3208         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3209     }
3210
3211     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3212     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3213     if (heightType == ExcludeMarginBorderPadding) {
3214         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3215         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3216     }
3217     return availableHeight;
3218 }
3219
3220 void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3221 {
3222     if (isTableCell()) {
3223         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3224         // we may just do it with an extra anonymous block inside the cell.
3225         marginBefore = 0;
3226         marginAfter = 0;
3227         return;
3228     }
3229
3230     // Margins are calculated with respect to the logical width of
3231     // the containing block (8.3)
3232     LayoutUnit cw = containingBlockLogicalWidthForContent();
3233     const RenderStyle& containingBlockStyle = containingBlock.style();
3234     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3235     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3236 }
3237
3238 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock)
3239 {
3240     LayoutUnit marginBefore;
3241     LayoutUnit marginAfter;
3242     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3243     containingBlock.setMarginBeforeForChild(*this, marginBefore);
3244     containingBlock.setMarginAfterForChild(*this, marginAfter);
3245 }
3246
3247 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3248 {
3249     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3250         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3251
3252 #if ENABLE(CSS_GRID_LAYOUT)
3253     if (hasOverrideContainingBlockLogicalWidth()) {
3254         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
3255             return overrideLogicalWidth.value();
3256     }
3257 #endif
3258
3259     if (is<RenderBox>(containingBlock)) {
3260         bool isFixedPosition = style().position() == FixedPosition;
3261
3262         RenderFlowThread* flowThread = flowThreadContainingBlock();
3263         if (!flowThread) {
3264             if (isFixedPosition && is<RenderView>(containingBlock))
3265                 return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition();
3266
3267             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3268         }
3269
3270         if (isFixedPosition && is<RenderNamedFlowThread>(containingBlock))
3271             return containingBlock.view().clientLogicalWidth();
3272
3273         if (!is<RenderBlock>(containingBlock))
3274             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3275
3276         const RenderBlock& cb = downcast<RenderBlock>(containingBlock);
3277         RenderBoxRegionInfo* boxInfo = nullptr;
3278         if (!region) {
3279             if (is<RenderFlowThread>(containingBlock) && !checkForPerpendicularWritingMode)
3280                 return downcast<RenderFlowThread>(containingBlock).contentLogicalWidthOfFirstRegion();
3281             if (isWritingModeRoot()) {
3282                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3283                 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3284                 if (cbRegion)
3285                     boxInfo = cb.renderBoxRegionInfo(cbRegion);
3286             }
3287         } else if (flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3288             RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3289             boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3290         }
3291         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3292     }
3293
3294     ASSERT(containingBlock.isInFlowPositioned());
3295
3296     const auto& flow = downcast<RenderInline>(containingBlock);
3297     InlineFlowBox* first = flow.firstLineBox();
3298     InlineFlowBox* last = flow.lastLineBox();
3299
3300     // If the containing block is empty, return a width of 0.
3301     if (!first || !last)
3302         return 0;
3303
3304     LayoutUnit fromLeft;
3305     LayoutUnit fromRight;
3306     if (containingBlock.style().isLeftToRightDirection()) {
3307         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3308         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3309     } else {
3310         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3311         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3312     }
3313
3314     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3315 }
3316
3317 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const
3318 {
3319     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3320         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3321
3322 #if ENABLE(CSS_GRID_LAYOUT)
3323     if (hasOverrideContainingBlockLogicalHeight()) {
3324         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
3325             return overrideLogicalHeight.value();
3326     }
3327 #endif
3328
3329     if (containingBlock.isBox()) {
3330         bool isFixedPosition = style().position() == FixedPosition;
3331
3332         if (isFixedPosition && is<RenderView>(containingBlock))
3333             return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition();
3334
3335         const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock();
3336         LayoutUnit result = cb.clientLogicalHeight();
3337         RenderFlowThread* flowThread = flowThreadContainingBlock();
3338         if (flowThread && is<RenderFlowThread>(containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3339             if (is<RenderNamedFlowThread>(containingBlock) && isFixedPosition)
3340                 return containingBlock.view().clientLogicalHeight();
3341             return downcast<RenderFlowThread>(containingBlock).contentLogicalHeightOfFirstRegion();
3342         }
3343         return result;
3344     }
3345         
3346     ASSERT(containingBlock.isInFlowPositioned());
3347
3348     const auto& flow = downcast<RenderInline>(containingBlock);
3349     InlineFlowBox* first = flow.firstLineBox();
3350     InlineFlowBox* last = flow.lastLineBox();
3351
3352     // If the containing block is empty, return a height of 0.
3353     if (!first || !last)
3354         return 0;
3355
3356     LayoutUnit heightResult;
3357     LayoutRect boundingBox = flow.linesBoundingBox();
3358     if (containingBlock.isHorizontalWritingMode())
3359         heightResult = boundingBox.height();
3360     else
3361         heightResult = boundingBox.width();
3362     heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter());
3363     return heightResult;
3364 }
3365
3366 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3367 {
3368     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3369         return;
3370
3371     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3372     if (child->parent()->style().direction() == LTR) {
3373         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft();
3374         for (auto* current = child->parent(); current && current != &containerBlock; current = current->container()) {
3375             if (!is<RenderBox>(*current))
3376                 continue;
3377             const auto& renderBox = downcast<RenderBox>(*current);
3378             staticPosition += renderBox.logicalLeft();
3379             if (renderBox.isInFlowPositioned())
3380                 staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3381             if (region && is<RenderBlock>(*current)) {
3382                 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3383                 region = currentBlock.clampToStartAndEndRegions(region);
3384                 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3385                 if (boxInfo)
3386                     staticPosition += boxInfo->logicalLeft();
3387             }
3388         }
3389         logicalLeft.setValue(Fixed, staticPosition);
3390     } else {
3391         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock.borderLogicalLeft();
3392         auto& enclosingBox = child->parent()->enclosingBox();
3393         if (&enclosingBox != &containerBlock && containerBlock.isDescendantOf(&enclosingBox)) {
3394             logicalRight.setValue(Fixed, staticPosition);
3395             return;
3396         }
3397
3398         staticPosition -= enclosingBox.logicalWidth();
3399         for (const RenderElement* current = &enclosingBox; current; current = current->container()) {
3400             if (!is<RenderBox>(*current))
3401                 continue;
3402
3403             if (current != &containerBlock) {
3404                 auto& renderBox = downcast<RenderBox>(*current);
3405                 staticPosition -= renderBox.logicalLeft();
3406                 if (renderBox.isInFlowPositioned())
3407                     staticPosition -= renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3408             }
3409             if (region && is<RenderBlock>(*current)) {
3410                 auto& currentBlock = downcast<RenderBlock>(*current);
3411                 region = currentBlock.clampToStartAndEndRegions(region);
3412                 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3413                 if (boxInfo) {
3414                     if (current != &containerBlock)
3415                         staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3416                     if (current == &enclosingBox)
3417                         staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3418                 }
3419             }
3420             if (current == &containerBlock)
3421                 break;
3422         }
3423         logicalRight.setValue(Fixed, staticPosition);
3424     }
3425 }
3426
3427 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3428 {
3429     if (isReplaced()) {
3430         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3431         // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3432         computePositionedLogicalWidthReplaced(computedValues);
3433         return;
3434     }
3435
3436     // QUESTIONS
3437     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3438     // the type 'static' in determining whether to calculate the static distance?
3439     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3440
3441     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3442     // than or less than the computed width().  Be careful of box-sizing and
3443     // percentage issues.
3444
3445     // The following is based off of the W3C Working Draft from April 11, 2006 of
3446     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3447     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3448     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3449     // correspond to text from the spec)
3450
3451
3452     // We don't use containingBlock(), since we may be positioned by an enclosing
3453     // relative positioned inline.
3454     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3455     
3456     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3457
3458     // Use the container block's direction except when calculating the static distance
3459     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3460     // of the CSS 2.1 test suite
3461     TextDirection containerDirection = containerBlock.style().direction();
3462
3463     bool isHorizontal = isHorizontalWritingMode();
3464     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3465     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3466     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3467
3468     Length logicalLeftLength = style().logicalLeft();
3469     Length logicalRightLength = style().logicalRight();
3470
3471     /*---------------------------------------------------------------------------*\
3472      * For the purposes of this section and the next, the term "static position"
3473      * (of an element) refers, roughly, to the position an element would have had
3474      * in the normal flow. More precisely:
3475      *
3476      * * The static position for 'left' is the distance from the left edge of the
3477      *   containing block to the left margin edge of a hypothetical box that would
3478      *   have been the first box of the element if its 'position' property had
3479      *   been 'static' and 'float' had been 'none'. The value is negative if the
3480      *   hypothetical box is to the left of the containing block.
3481      * * The static position for 'right' is the distance from the right edge of the
3482      *   containing block to the right margin edge of the same hypothetical box as
3483      *   above. The value is positive if the hypothetical box is to the left of the
3484      *   containing block's edge.
3485      *
3486      * But rather than actually calculating the dimensions of that hypothetical box,
3487      * user agents are free to make a guess at its probable position.
3488      *
3489      * For the purposes of calculating the static position, the containing block of
3490      * fixed positioned elements is the initial containing block instead of the
3491      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3492      * origin.
3493     \*---------------------------------------------------------------------------*/
3494
3495     // see FIXME 1
3496     // Calculate the static distance if needed.
3497     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3498     
3499     // Calculate constraint equation values for 'width' case.
3500     computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection,
3501                                        containerLogicalWidth, bordersPlusPadding,
3502                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3503                                        computedValues);
3504
3505     // Calculate constraint equation values for 'max-width' case.
3506     if (!style().logicalMaxWidth().isUndefined()) {
3507         LogicalExtentComputedValues maxValues;
3508
3509         computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection,
3510                                            containerLogicalWidth, bordersPlusPadding,
3511                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3512                                            maxValues);
3513
3514         if (computedValues.m_extent > maxValues.m_extent) {
3515             computedValues.m_extent = maxValues.m_extent;
3516             computedValues.m_position = maxValues.m_position;
3517             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3518             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3519         }
3520     }
3521
3522     // Calculate constraint equation values for 'min-width' case.
3523     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3524         LogicalExtentComputedValues minValues;
3525
3526         computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection,
3527                                            containerLogicalWidth, bordersPlusPadding,
3528                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3529                                            minValues);
3530
3531         if (computedValues.m_extent < minValues.m_extent) {
3532             computedValues.m_extent = minValues.m_extent;
3533             computedValues.m_position = minValues.m_position;
3534             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3535             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3536         }
3537     }
3538
3539 #if ENABLE(CSS_GRID_LAYOUT)
3540     if (!style().hasStaticInlinePosition(isHorizontal))
3541         computedValues.m_position += extraInlineOffset();
3542 #endif
3543
3544     computedValues.m_extent += bordersPlusPadding;
3545     if (is<RenderBox>(containerBlock)) {
3546         auto& containingBox = downcast<RenderBox>(containerBlock);
3547         if (containingBox.shouldPlaceBlockDirectionScrollbarOnLeft())
3548             computedValues.m_position += containingBox.verticalScrollbarWidth();
3549     }
3550     
3551     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3552     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3553     RenderFlowThread* flowThread = flowThreadContainingBlock();
3554     if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) {
3555         ASSERT(containerBlock.canHaveBoxInfoInRegion());
3556         LayoutUnit logicalLeftPos = computedValues.m_position;
3557         const RenderBlock& renderBlock = downcast<RenderBlock>(containerBlock);
3558         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3559         RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3560         if (cbRegion) {
3561             RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3562             if (boxInfo) {
3563                 logicalLeftPos += boxInfo->logicalLeft();
3564                 computedValues.m_position = logicalLeftPos;
3565             }
3566         }
3567     }
3568 }
3569
3570 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth)
3571 {
3572     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3573     // 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.
3574     if (containerBlock.isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock.style().isFlippedBlocksWritingMode()) {
3575         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3576         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderRight() : containerBlock.borderBottom());
3577     } else
3578         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderLeft() : containerBlock.borderTop());
3579 }
3580
3581 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject& containerBlock, TextDirection containerDirection,
3582                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3583                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3584                                                    LogicalExtentComputedValues& computedValues) const
3585 {
3586     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3587     if (widthType == MinSize && logicalWidth.isAuto())
3588         logicalWidth = Length(0, Fixed);
3589     else if (logicalWidth.isIntrinsic())
3590         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3591
3592     // 'left' and 'right' cannot both be 'auto' because one would of been
3593     // converted to the static position already
3594     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3595
3596     LayoutUnit logicalLeftValue = 0;
3597
3598     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3599
3600     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3601     bool logicalLeftIsAuto = logicalLeft.isAuto();
3602     bool logicalRightIsAuto = logicalRight.isAuto();
3603     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3604     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3605
3606     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3607         /*-----------------------------------------------------------------------*\
3608          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3609          * right' are 'auto', solve the equation under the extra constraint that
3610          * the two margins get equal values, unless this would make them negative,
3611          * in which case when direction of the containing block is 'ltr' ('rtl'),
3612          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3613          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3614          * solve the equation for that value. If the values are over-constrained,
3615          * ignore the value for 'left' (in case the 'direction' property of the
3616          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3617          * and solve for that value.
3618         \*-----------------------------------------------------------------------*/
3619         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3620         // case because the value is not used for any further calculations.
3621
3622         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3623         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3624
3625         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3626
3627         // Margins are now the only unknown
3628         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3629             // Both margins auto, solve for equality
3630             if (availableSpace >= 0) {
3631                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3632                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3633             } else {
3634                 // Use the containing block's direction rather than the parent block's
3635                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3636                 if (containerDirection == LTR) {
3637                     marginLogicalLeftValue = 0;
3638                     marginLogicalRightValue = availableSpace; // will be negative
3639                 } else {
3640                     marginLogicalLeftValue = availableSpace; // will be negative
3641                     marginLogicalRightValue = 0;
3642                 }
3643             }
3644         } else if (marginLogicalLeft.isAuto()) {
3645             // Solve for left margin
3646             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3647             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3648         } else if (marginLogicalRight.isAuto()) {
3649             // Solve for right margin
3650             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3651             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3652         } else {
3653             // Over-constrained, solve for left if direction is RTL
3654             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3655             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3656
3657             // Use the containing block's direction rather than the parent block's
3658             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3659             if (containerDirection == RTL)
3660                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3661         }
3662     } else {
3663         /*--------------------------------------------------------------------*\
3664          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3665          * to 0, and pick the one of the following six rules that applies.
3666          *
3667          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3668          *    width is shrink-to-fit. Then solve for 'left'
3669          *
3670          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3671          * ------------------------------------------------------------------
3672          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3673          *    the 'direction' property of the containing block is 'ltr' set
3674          *    'left' to the static position, otherwise set 'right' to the
3675          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3676          *    or 'right' (if 'direction' is 'ltr').
3677          * ------------------------------------------------------------------
3678          *
3679          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3680          *    width is shrink-to-fit . Then solve for 'right'
3681          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3682          *    for 'left'
3683          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3684          *    for 'width'
3685          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3686          *    for 'right'
3687          *
3688          * Calculation of the shrink-to-fit width is similar to calculating the
3689          * width of a table cell using the automatic table layout algorithm.
3690          * Roughly: calculate the preferred width by formatting the content
3691          * without breaking lines other than where explicit line breaks occur,
3692          * and also calculate the preferred minimum width, e.g., by trying all
3693          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3694          * Thirdly, calculate the available width: this is found by solving
3695          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3696          * to 0.
3697          *
3698          * Then the shrink-to-fit width is:
3699          * min(max(preferred minimum width, available width), preferred width).
3700         \*--------------------------------------------------------------------*/
3701         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3702         // because the value is not used for any further calculations.
3703
3704         // Calculate margins, 'auto' margins are ignored.
3705         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3706         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3707
3708         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3709
3710         // FIXME: Is there a faster way to find the correct case?
3711         // Use rule/case that applies.
3712         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3713             // RULE 1: (use shrink-to-fit for width, and solve of left)
3714             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3715
3716             // FIXME: would it be better to have shrink-to-fit in one step?
3717             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3718             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3719             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3720             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3721             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3722         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3723             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3724             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3725
3726             // FIXME: would it be better to have shrink-to-fit in one step?
3727             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3728             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3729             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3730             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3731         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3732             // RULE 4: (solve for left)
3733             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3734             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3735         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3736             // RULE 5: (solve for width)
3737             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3738             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3739         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3740             // RULE 6: (no need solve for right)
3741             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3742             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3743         }
3744     }
3745
3746     // Use computed values to calculate the horizontal position.
3747
3748     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3749     // positioned, inline because right now, it is using the logical left position
3750     // of the first line box when really it should use the last line box.  When
3751     // this is fixed elsewhere, this block should be removed.
3752     if (is<RenderInline>(containerBlock) && !containerBlock.style().isLeftToRightDirection()) {
3753         const auto& flow = downcast<RenderInline>(containerBlock);
3754         InlineFlowBox* firstLine = flow.firstLineBox();
3755         InlineFlowBox* lastLine = flow.lastLineBox();
3756         if (firstLine && lastLine && firstLine != lastLine) {
3757             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3758             return;
3759         }
3760     }
3761
3762     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3763     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3764 }
3765
3766 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject& containerBlock)
3767 {
3768     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3769         return;
3770     
3771     // FIXME: The static distance computation has not been patched for mixed writing modes.
3772     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock.borderBefore();
3773     for (RenderElement* container = child->parent(); container && container != &containerBlock; container = container->container()) {
3774         if (!is<RenderBox>(*container))
3775             continue;
3776         const auto& renderBox = downcast<RenderBox>(*container);
3777         if (!is<RenderTableRow>(renderBox))
3778             staticLogicalTop += renderBox.logicalTop();
3779         if (renderBox.isInFlowPositioned())
3780             staticLogicalTop += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().height() : renderBox.offsetForInFlowPosition().width();
3781     }
3782     logicalTop.setValue(Fixed, staticLogicalTop);
3783 }
3784
3785 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3786 {
3787     if (isReplaced()) {
3788         computePositionedLogicalHeightReplaced(computedValues);
3789         return;
3790     }
3791
3792     // The following is based off of the W3C Working Draft from April 11, 2006 of
3793     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3794     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3795     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3796     // correspond to text from the spec)
3797
3798
3799     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3800     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3801
3802     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3803
3804     const RenderStyle& styleToUse = style();
3805     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3806     const Length marginBefore = styleToUse.marginBefore();
3807     const Length marginAfter = styleToUse.marginAfter();
3808     Length logicalTopLength = styleToUse.logicalTop();
3809     Length logicalBottomLength = styleToUse.logicalBottom();
3810
3811     /*---------------------------------------------------------------------------*\
3812      * For the purposes of this section and the next, the term "static position"
3813      * (of an element) refers, roughly, to the position an element would have had
3814      * in the normal flow. More precisely, the static position for 'top' is the
3815      * distance from the top edge of the containing block to the top margin edge
3816      * of a hypothetical box that would have been the first box of the element if
3817      * its 'position' property had been 'static' and 'float' had been 'none'. The
3818      * value is negative if the hypothetical box is above the containing block.