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