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