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