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