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