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