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