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