Update Grid Layout to use fewer magic -1s
[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     if (!context)
1624         shouldDrawBackgroundInSeparateBuffer = false;
1625
1626     BaseBackgroundColorUsage baseBgColorUsage = BaseBackgroundColorUse;
1627
1628     if (shouldDrawBackgroundInSeparateBuffer) {
1629         paintFillLayer(paintInfo, c, *layers.rbegin(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1630         baseBgColorUsage = BaseBackgroundColorSkip;
1631         context->beginTransparencyLayer(1);
1632     }
1633
1634     Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1635     for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1636         paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1637
1638     if (shouldDrawBackgroundInSeparateBuffer)
1639         context->endTransparencyLayer();
1640 }
1641
1642 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1643     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1644 {
1645     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1646 }
1647
1648 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1649 {
1650     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1651         if (curLayer->image() && image == curLayer->image()->data())
1652             return true;
1653     }
1654
1655     return false;
1656 }
1657
1658 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1659 {
1660     if (!parent())
1661         return;
1662
1663     if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1664         (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1665         repaint();
1666         return;
1667     }
1668
1669 #if ENABLE(CSS_SHAPES)
1670     ShapeValue* shapeOutsideValue = style().shapeOutside();
1671     if (!view().frameView().isInLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1672         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1673         markShapeOutsideDependentsForLayout();
1674     }
1675 #endif
1676
1677     bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1678     if (!didFullRepaint)
1679         repaintLayerRectsForImage(image, style().maskLayers(), false);
1680
1681     if (!isComposited())
1682         return;
1683
1684     if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1685         layer()->contentChanged(MaskImageChanged);
1686     if (layersUseImage(image, style().backgroundLayers()))
1687         layer()->contentChanged(BackgroundImageChanged);
1688 }
1689
1690 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1691 {
1692     LayoutRect rendererRect;
1693     RenderBox* layerRenderer = nullptr;
1694
1695     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1696         if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) {
1697             // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1698             bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1699             if (!layerRenderer) {
1700                 if (drawingRootBackground) {
1701                     layerRenderer = &view();
1702
1703                     LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1704                     LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1705
1706                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1707                         -layerRenderer->marginTop(),
1708                         std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1709                         std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1710                 } else {
1711                     layerRenderer = this;
1712                     rendererRect = borderBoxRect();
1713                 }
1714             }
1715             // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping)
1716             BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *curLayer, LayoutPoint(), rendererRect);
1717             if (geometry.hasNonLocalGeometry()) {
1718                 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1719                 // in order to get the right destRect, just repaint the entire renderer.
1720                 layerRenderer->repaint();
1721                 return true;
1722             }
1723             
1724             LayoutRect rectToRepaint = geometry.destRect();
1725             bool shouldClipToLayer = true;
1726
1727             // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1728             // extendedBackground. We should only extend the rect if it is already extending the full width or height
1729             // of the rendererRect.
1730             if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1731                 shouldClipToLayer = false;
1732                 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1733                 if (rectToRepaint.width() == rendererRect.width()) {
1734                     rectToRepaint.move(extendedBackgroundRect.x(), 0);
1735                     rectToRepaint.setWidth(extendedBackgroundRect.width());
1736                 }
1737                 if (rectToRepaint.height() == rendererRect.height()) {
1738                     rectToRepaint.move(0, extendedBackgroundRect.y());
1739                     rectToRepaint.setHeight(extendedBackgroundRect.height());
1740                 }
1741             }
1742
1743             layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1744             if (geometry.destRect() == rendererRect)
1745                 return true;
1746         }
1747     }
1748     return false;
1749 }
1750
1751 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1752 {
1753     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1754         return false;
1755         
1756     bool isControlClip = hasControlClip();
1757     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1758     
1759     if (!isControlClip && !isOverflowClip)
1760         return false;
1761     
1762     if (paintInfo.phase == PaintPhaseOutline)
1763         paintInfo.phase = PaintPhaseChildOutlines;
1764     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1765         paintInfo.phase = PaintPhaseBlockBackground;
1766         paintObject(paintInfo, accumulatedOffset);
1767         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1768     }
1769     float deviceScaleFactor = document().deviceScaleFactor();
1770     FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1771     paintInfo.context->save();
1772     if (style().hasBorderRadius())
1773         paintInfo.context->clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1774     paintInfo.context->clip(clipRect);
1775     return true;
1776 }
1777
1778 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1779 {
1780     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1781
1782     paintInfo.context->restore();
1783     if (originalPhase == PaintPhaseOutline) {
1784         paintInfo.phase = PaintPhaseSelfOutline;
1785         paintObject(paintInfo, accumulatedOffset);
1786         paintInfo.phase = originalPhase;
1787     } else if (originalPhase == PaintPhaseChildBlockBackground)
1788         paintInfo.phase = originalPhase;
1789 }
1790
1791 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1792 {
1793     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1794     // here.
1795     LayoutRect clipRect = borderBoxRectInRegion(region);
1796     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1797     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1798
1799     // Subtract out scrollbars if we have them.
1800      if (layer()) {
1801         if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1802             clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1803         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1804      }
1805
1806     return clipRect;
1807 }
1808
1809 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1810 {
1811     LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1812     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1813
1814     if (!style().clipLeft().isAuto()) {
1815         LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1816         clipRect.move(c, 0);
1817         clipRect.contract(c, 0);
1818     }
1819
1820     // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1821     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1822
1823     if (!style().clipRight().isAuto())
1824         clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1825
1826     if (!style().clipTop().isAuto()) {
1827         LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1828         clipRect.move(0, c);
1829         clipRect.contract(0, c);
1830     }
1831
1832     if (!style().clipBottom().isAuto())
1833         clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1834
1835     return clipRect;
1836 }
1837
1838 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
1839 {    
1840     RenderRegion* containingBlockRegion = nullptr;
1841     LayoutUnit logicalTopPosition = logicalTop();
1842     if (region) {
1843         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1844         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1845         containingBlockRegion = cb->clampToStartAndEndRegions(region);
1846     }
1847
1848     LayoutUnit logicalHeight = cb->logicalHeightForChild(*this);
1849     LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd;
1850
1851     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1852     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1853     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1854     // 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
1855     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1856     if (childMarginStart > 0) {
1857         LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
1858         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1859         LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight);
1860         if (startOffset > startContentSideWithMargin)
1861             result += childMarginStart;
1862         else
1863             result += startOffset - startContentSide;
1864     }
1865     
1866     if (childMarginEnd > 0) {
1867         LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
1868         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1869         LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight);
1870         if (endOffset > endContentSideWithMargin)
1871             result += childMarginEnd;
1872         else
1873             result += endOffset - endContentSide;
1874     }
1875
1876     return result;
1877 }
1878
1879 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1880 {
1881 #if ENABLE(CSS_GRID_LAYOUT)
1882     if (hasOverrideContainingBlockLogicalWidth()) {
1883         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
1884             return overrideLogicalWidth.value();
1885     }
1886 #endif
1887
1888     if (RenderBlock* cb = containingBlock())
1889         return cb->availableLogicalWidth();
1890     return LayoutUnit();
1891 }
1892
1893 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1894 {
1895 #if ENABLE(CSS_GRID_LAYOUT)
1896     if (hasOverrideContainingBlockLogicalHeight()) {
1897         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1898             return overrideLogicalHeight.value();
1899     }
1900 #endif
1901
1902     if (RenderBlock* cb = containingBlock())
1903         return cb->availableLogicalHeight(heightType);
1904     return LayoutUnit();
1905 }
1906
1907 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1908 {
1909     if (!region)
1910         return containingBlockLogicalWidthForContent();
1911
1912     RenderBlock* cb = containingBlock();
1913     RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1914     // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1915     // If it should, the following line should call containingBlockLogicalWidthForContent.
1916     LayoutUnit result = cb->availableLogicalWidth();
1917     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1918     if (!boxInfo)
1919         return result;
1920     return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1921 }
1922
1923 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1924 {
1925     RenderBlock* cb = containingBlock();
1926     RenderRegion* containingBlockRegion = nullptr;
1927     LayoutUnit logicalTopPosition = logicalTop();
1928     if (region) {
1929         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1930         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1931         containingBlockRegion = cb->clampToStartAndEndRegions(region);
1932     }
1933     return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1934 }
1935
1936 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1937 {
1938 #if ENABLE(CSS_GRID_LAYOUT)
1939     if (hasOverrideContainingBlockLogicalHeight()) {
1940         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1941             return overrideLogicalHeight.value();
1942     }
1943 #endif
1944
1945     RenderBlock* cb = containingBlock();
1946     if (cb->hasOverrideLogicalContentHeight())
1947         return cb->overrideLogicalContentHeight();
1948
1949     const RenderStyle& containingBlockStyle = cb->style();
1950     Length logicalHeightLength = containingBlockStyle.logicalHeight();
1951
1952     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1953     if (!logicalHeightLength.isFixed()) {
1954         LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1955         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1956         return std::min(fillAvailableExtent, fillFallbackExtent);
1957     }
1958
1959     // Use the content box logical height as specified by the style.
1960     return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value()));
1961 }
1962
1963 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1964 {
1965     if (repaintContainer == this)
1966         return;
1967
1968     if (view().layoutStateEnabled() && !repaintContainer) {
1969         LayoutState* layoutState = view().layoutState();
1970         LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1971         if (style().hasInFlowPosition() && layer())
1972             offset += layer()->offsetForInFlowPosition();
1973         transformState.move(offset);
1974         return;
1975     }
1976
1977     bool containerSkipped;
1978     RenderElement* container = this->container(repaintContainer, &containerSkipped);
1979     if (!container)
1980         return;
1981
1982     bool isFixedPos = style().position() == FixedPosition;
1983     // If this box has a transform, it acts as a fixed position container for fixed descendants,
1984     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1985     if (hasTransform() && !isFixedPos)
1986         mode &= ~IsFixed;
1987     else if (isFixedPos)
1988         mode |= IsFixed;
1989
1990     if (wasFixed)
1991         *wasFixed = mode & IsFixed;
1992     
1993     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
1994     
1995     bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
1996     if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
1997         TransformationMatrix t;
1998         getTransformFromContainer(container, containerOffset, t);
1999         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2000     } else
2001         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2002
2003     if (containerSkipped) {
2004         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
2005         // to just subtract the delta between the repaintContainer and o.
2006         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
2007         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2008         return;
2009     }
2010
2011     mode &= ~ApplyContainerFlip;
2012
2013     // For fixed positioned elements inside out-of-flow named flows, we do not want to
2014     // map their position further to regions based on their coordinates inside the named flows.
2015     if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
2016         container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2017     else
2018         container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed);
2019 }
2020
2021 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2022 {
2023     ASSERT(ancestorToStopAt != this);
2024
2025     bool ancestorSkipped;
2026     RenderElement* container = this->container(ancestorToStopAt, &ancestorSkipped);
2027     if (!container)
2028         return nullptr;
2029
2030     bool isFixedPos = style().position() == FixedPosition;
2031     LayoutSize adjustmentForSkippedAncestor;
2032     if (ancestorSkipped) {
2033         // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
2034         // to just subtract the delta between the ancestor and container.
2035         adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2036     }
2037
2038     bool offsetDependsOnPoint = false;
2039     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2040
2041     bool preserve3D = container->style().preserves3D() || style().preserves3D();
2042     if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2043         TransformationMatrix t;
2044         getTransformFromContainer(container, containerOffset, t);
2045         t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2046         
2047         geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2048     } else {
2049         containerOffset += adjustmentForSkippedAncestor;
2050         geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2051     }
2052     
2053     return ancestorSkipped ? ancestorToStopAt : container;
2054 }
2055
2056 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2057 {
2058     bool isFixedPos = style().position() == FixedPosition;
2059     if (hasTransform() && !isFixedPos) {
2060         // If this box has a transform, it acts as a fixed position container for fixed descendants,
2061         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2062         mode &= ~IsFixed;
2063     } else if (isFixedPos)
2064         mode |= IsFixed;
2065
2066     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2067 }
2068
2069 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2070 {
2071     // A region "has" boxes inside it without being their container. 
2072     ASSERT(&renderer == container() || is<RenderRegion>(renderer));
2073
2074     LayoutSize offset;    
2075     if (isInFlowPositioned())
2076         offset += offsetForInFlowPosition();
2077
2078     if (!isInline() || isReplaced())
2079         offset += topLeftLocationOffset();
2080
2081     if (is<RenderBox>(renderer))
2082         offset -= downcast<RenderBox>(renderer).scrolledContentOffset();
2083
2084     if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2085         offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2086
2087     if (offsetDependsOnPoint)
2088         *offsetDependsOnPoint |= is<RenderFlowThread>(renderer);
2089
2090     return offset;
2091 }
2092
2093 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2094 {
2095     return std::make_unique<InlineElementBox>(*this);
2096 }
2097
2098 void RenderBox::dirtyLineBoxes(bool fullLayout)
2099 {
2100     if (m_inlineBoxWrapper) {
2101         if (fullLayout) {
2102             delete m_inlineBoxWrapper;
2103             m_inlineBoxWrapper = nullptr;
2104         } else
2105             m_inlineBoxWrapper->dirtyLineBoxes();
2106     }
2107 }
2108
2109 void RenderBox::positionLineBox(InlineElementBox& box)
2110 {
2111     if (isOutOfFlowPositioned()) {
2112         // Cache the x position only if we were an INLINE type originally.
2113         bool wasInline = style().isOriginalDisplayInlineType();
2114         if (wasInline) {
2115             // The value is cached in the xPos of the box.  We only need this value if
2116             // our object was inline originally, since otherwise it would have ended up underneath
2117             // the inlines.
2118             RootInlineBox& rootBox = box.root();
2119             rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2120             if (style().hasStaticInlinePosition(box.isHorizontal()))
2121                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2122         } else {
2123             // Our object was a block originally, so we make our normal flow position be
2124             // just below the line box (as though all the inlines that came before us got
2125             // wrapped in an anonymous block, which is what would have happened had we been
2126             // in flow).  This value was cached in the y() of the box.
2127             layer()->setStaticBlockPosition(box.logicalTop());
2128             if (style().hasStaticBlockPosition(box.isHorizontal()))
2129                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2130         }
2131
2132         // Nuke the box.
2133         box.removeFromParent();
2134         delete &box;
2135         return;
2136     }
2137
2138     if (isReplaced()) {
2139         setLocation(LayoutPoint(box.topLeft()));
2140         setInlineBoxWrapper(&box);
2141     }
2142 }
2143
2144 void RenderBox::deleteLineBoxWrapper()
2145 {
2146     if (m_inlineBoxWrapper) {
2147         if (!documentBeingDestroyed())
2148             m_inlineBoxWrapper->removeFromParent();
2149         delete m_inlineBoxWrapper;
2150         m_inlineBoxWrapper = nullptr;
2151     }
2152 }
2153
2154 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2155 {
2156     if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2157         return LayoutRect();
2158
2159     LayoutRect r = visualOverflowRect();
2160
2161     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2162     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2163     r.move(view().layoutDelta());
2164     
2165     // We have to use maximalOutlineSize() because a child might have an outline
2166     // that projects outside of our overflowRect.
2167     ASSERT(style().outlineSize() <= view().maximalOutlineSize());
2168     r.inflate(view().maximalOutlineSize());
2169     
2170     computeRectForRepaint(repaintContainer, r);
2171     return r;
2172 }
2173
2174 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2175 {
2176 #if PLATFORM(IOS)
2177     if (!repaintContainer || repaintContainer != containerBox)
2178         return true;
2179
2180     return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2181 #else
2182     UNUSED_PARAM(repaintContainer);
2183     UNUSED_PARAM(containerBox);
2184     return true;
2185 #endif
2186 }
2187
2188 void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
2189 {
2190     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2191     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2192     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2193     // properly even during layout, since the rect remains flipped all the way until the end.
2194     //
2195     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2196     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2197     // physical coordinate space of the repaintContainer.
2198     const RenderStyle& styleToUse = style();
2199     // LayoutState is only valid for root-relative, non-fixed position repainting
2200     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2201         LayoutState* layoutState = view().layoutState();
2202
2203         if (layer() && layer()->transform())
2204             rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2205
2206         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2207         if (styleToUse.hasInFlowPosition() && layer())
2208             rect.move(layer()->offsetForInFlowPosition());
2209
2210         rect.moveBy(location());
2211         rect.move(layoutState->m_paintOffset);
2212         if (layoutState->m_clipped)
2213             rect.intersect(layoutState->m_clipRect);
2214         return;
2215     }
2216
2217     if (hasReflection())
2218         rect.unite(reflectedRect(rect));
2219
2220     if (repaintContainer == this) {
2221         if (repaintContainer->style().isFlippedBlocksWritingMode())
2222             flipForWritingMode(rect);
2223         return;
2224     }
2225
2226     bool containerSkipped;
2227     auto* renderer = container(repaintContainer, &containerSkipped);
2228     if (!renderer)
2229         return;
2230     
2231     EPosition position = styleToUse.position();
2232
2233     // This code isn't necessary for in-flow RenderFlowThreads.
2234     // Don't add the location of the region in the flow thread for absolute positioned
2235     // elements because their absolute position already pushes them down through
2236     // the regions so adding this here and then adding the topLeft again would cause
2237     // us to add the height twice.
2238     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2239     // will already contain the portion rect of the region.
2240     if (renderer->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2241         RenderRegion* firstRegion = nullptr;
2242         RenderRegion* lastRegion = nullptr;
2243         if (downcast<RenderFlowThread>(*renderer).getRegionRangeForBox(this, firstRegion, lastRegion))
2244             rect.moveBy(firstRegion->flowThreadPortionRect().location());
2245     }
2246
2247     if (isWritingModeRoot() && !isOutOfFlowPositioned())
2248         flipForWritingMode(rect);
2249
2250     LayoutSize locationOffset = this->locationOffset();
2251     // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2252     if (isRenderReplaced() && isWidget()) {
2253         LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2254         rect.expand(locationOffset - flooredLocationOffset);
2255         locationOffset = flooredLocationOffset;
2256     }
2257     LayoutPoint topLeft = rect.location();
2258     topLeft.move(locationOffset);
2259
2260     // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2261     // in the parent's coordinate space that encloses us.
2262     if (hasLayer() && layer()->transform()) {
2263         fixed = position == FixedPosition;
2264         rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2265         topLeft = rect.location();
2266         topLeft.move(locationOffset);
2267     } else if (position == FixedPosition)
2268         fixed = true;
2269
2270     if (position == AbsolutePosition && renderer->isInFlowPositioned() && is<RenderInline>(*renderer))
2271         topLeft += downcast<RenderInline>(*renderer).offsetForInFlowPositionedInline(this);
2272     else if (styleToUse.hasInFlowPosition() && layer()) {
2273         // Apply the relative position offset when invalidating a rectangle.  The layer
2274         // is translated, but the render box isn't, so we need to do this to get the
2275         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2276         // flag on the RenderObject has been cleared, so use the one on the style().
2277         topLeft += layer()->offsetForInFlowPosition();
2278     }
2279
2280     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2281     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2282     rect.setLocation(topLeft);
2283     if (renderer->hasOverflowClip()) {
2284         RenderBox& containerBox = downcast<RenderBox>(*renderer);
2285         if (shouldApplyContainersClipAndOffset(repaintContainer, &containerBox)) {
2286             containerBox.applyCachedClipAndScrollOffsetForRepaint(rect);
2287             if (rect.isEmpty())
2288                 return;
2289         }
2290     }
2291
2292     if (containerSkipped) {
2293         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2294         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*renderer);
2295         rect.move(-containerOffset);
2296         return;
2297     }
2298
2299     renderer->computeRectForRepaint(repaintContainer, rect, fixed);
2300 }
2301
2302 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2303 {
2304     if (oldRect.location() != m_frameRect.location()) {
2305         LayoutRect newRect = m_frameRect;
2306         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2307         // since the object may not have gotten a layout.
2308         m_frameRect = oldRect;
2309         repaint();
2310         repaintOverhangingFloats(true);
2311         m_frameRect = newRect;
2312         repaint();
2313         repaintOverhangingFloats(true);
2314     }
2315 }
2316
2317 void RenderBox::repaintOverhangingFloats(bool)
2318 {
2319 }
2320
2321 void RenderBox::updateLogicalWidth()
2322 {
2323     LogicalExtentComputedValues computedValues;
2324     computeLogicalWidthInRegion(computedValues);
2325
2326     setLogicalWidth(computedValues.m_extent);
2327     setLogicalLeft(computedValues.m_position);
2328     setMarginStart(computedValues.m_margins.m_start);
2329     setMarginEnd(computedValues.m_margins.m_end);
2330 }
2331
2332 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2333 {
2334     computedValues.m_extent = logicalWidth();
2335     computedValues.m_position = logicalLeft();
2336     computedValues.m_margins.m_start = marginStart();
2337     computedValues.m_margins.m_end = marginEnd();
2338
2339     if (isOutOfFlowPositioned()) {
2340         // FIXME: This calculation is not patched for block-flow yet.
2341         // https://bugs.webkit.org/show_bug.cgi?id=46500
2342         computePositionedLogicalWidth(computedValues, region);
2343         return;
2344     }
2345
2346     // If layout is limited to a subtree, the subtree root's logical width does not change.
2347     if (element() && !view().frameView().layoutPending() && view().frameView().layoutRoot() == this)
2348         return;
2349
2350     // The parent box is flexing us, so it has increased or decreased our
2351     // width.  Use the width from the style context.
2352     // FIXME: Account for block-flow in flexible boxes.
2353     // https://bugs.webkit.org/show_bug.cgi?id=46418
2354     if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()
2355 #if ENABLE(CSS_GRID_LAYOUT)
2356         || parent()->isRenderGrid()
2357 #endif
2358     ))) {
2359         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2360         return;
2361     }
2362
2363     // FIXME: Account for block-flow in flexible boxes.
2364     // https://bugs.webkit.org/show_bug.cgi?id=46418
2365     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2366     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2367     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2368
2369     const RenderStyle& styleToUse = style();
2370     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2371
2372     RenderBlock* cb = containingBlock();
2373     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2374     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2375     
2376     if (isInline() && !isInlineBlockOrInlineTable()) {
2377         // just calculate margins
2378         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2379         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2380         if (treatAsReplaced)
2381             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2382         return;
2383     }
2384
2385     // Width calculations
2386     if (treatAsReplaced)
2387         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2388     else {
2389         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2390         if (hasPerpendicularContainingBlock)
2391             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2392         LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2393         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2394     }
2395
2396     // Margin calculations.
2397     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2398         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2399         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2400     } else {
2401         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2402         if (avoidsFloats() && cb->containsFloats())
2403             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2404         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2405         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2406             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2407             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2408     }
2409     
2410     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2411         && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated()
2412 #if ENABLE(CSS_GRID_LAYOUT)
2413         && !cb->isRenderGrid()
2414 #endif
2415         ) {
2416         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
2417         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2418         if (hasInvertedDirection)
2419             computedValues.m_margins.m_start = newMargin;
2420         else
2421             computedValues.m_margins.m_end = newMargin;
2422     }
2423 }
2424
2425 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2426 {
2427     LayoutUnit marginStart = 0;
2428     LayoutUnit marginEnd = 0;
2429     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2430 }
2431
2432 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2433 {
2434     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2435     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2436     return availableLogicalWidth - marginStart - marginEnd;
2437 }
2438
2439 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2440 {
2441     if (logicalWidthLength.type() == FillAvailable)
2442         return fillAvailableMeasure(availableLogicalWidth);
2443
2444     LayoutUnit minLogicalWidth = 0;
2445     LayoutUnit maxLogicalWidth = 0;
2446     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2447
2448     if (logicalWidthLength.type() == MinContent)
2449         return minLogicalWidth + borderAndPadding;
2450
2451     if (logicalWidthLength.type() == MaxContent)
2452         return maxLogicalWidth + borderAndPadding;
2453
2454     if (logicalWidthLength.type() == FitContent) {
2455         minLogicalWidth += borderAndPadding;
2456         maxLogicalWidth += borderAndPadding;
2457         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2458     }
2459
2460     ASSERT_NOT_REACHED();
2461     return 0;
2462 }
2463
2464 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2465     const RenderBlock* cb, RenderRegion* region) const
2466 {
2467     if (!logicalWidth.isIntrinsicOrAuto()) {
2468         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2469         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2470     }
2471
2472     if (logicalWidth.isIntrinsic())
2473         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2474
2475     LayoutUnit marginStart = 0;
2476     LayoutUnit marginEnd = 0;
2477     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2478
2479     if (shrinkToAvoidFloats() && cb->containsFloats())
2480         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2481
2482     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2483         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2484     return logicalWidthResult;
2485 }
2486
2487 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2488 {
2489     auto parent = flexitem.parent();
2490     return RenderStyle::resolveAlignment(parent->style(), flexitem.style(), ItemPositionStretch) == ItemPositionStretch;
2491 }
2492
2493 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2494 {
2495     auto parent = flexitem.parent();
2496     if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2497         return true;
2498
2499     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2500     if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2501         return true;
2502     return false;
2503 }
2504
2505 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2506 {
2507     // Anonymous inline blocks always fill the width of their containing block.
2508     if (isAnonymousInlineBlock())
2509         return false;
2510
2511     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2512     // but they allow text to sit on the same line as the marquee.
2513     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2514         return true;
2515
2516     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2517     // min-width and width.  max-width is only clamped if it is also intrinsic.
2518     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2519     if (logicalWidth.type() == Intrinsic)
2520         return true;
2521
2522     // Children of a horizontal marquee do not fill the container by default.
2523     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2524     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2525     // block-flow (as well as how marquee overflow should relate to block flow).
2526     // https://bugs.webkit.org/show_bug.cgi?id=46472
2527     if (parent()->style().overflowX() == OMARQUEE) {
2528         EMarqueeDirection dir = parent()->style().marqueeDirection();
2529         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2530             return true;
2531     }
2532
2533     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2534     // In the case of columns that have a stretch alignment, we layout at the stretched size
2535     // to avoid an extra layout when applying alignment.
2536     if (parent()->isFlexibleBox()) {
2537         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2538         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2539             return true;
2540         if (!flexItemHasStretchAlignment(*this))
2541             return true;
2542     }
2543
2544     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2545     // that don't stretch their kids lay out their children at their intrinsic widths.
2546     // FIXME: Think about block-flow here.
2547     // https://bugs.webkit.org/show_bug.cgi?id=46473
2548     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2549         return true;
2550
2551     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2552     // stretching column flexbox.
2553     // FIXME: Think about block-flow here.
2554     // https://bugs.webkit.org/show_bug.cgi?id=46473
2555     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2556         return true;
2557
2558     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2559         return true;
2560
2561     return false;
2562 }
2563
2564 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2565 {
2566     const RenderStyle& containingBlockStyle = containingBlock->style();
2567     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2568     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2569
2570     if (isFloating() || isInline()) {
2571         // Inline blocks/tables and floats don't have their margins increased.
2572         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2573         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2574         return;
2575     }
2576
2577     // Case One: The object is being centered in the containing block's available logical width.
2578     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2579         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) {
2580         // Other browsers center the margin box for align=center elements so we match them here.
2581         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2582         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2583         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2584         marginStart = centeredMarginBoxStart + marginStartWidth;
2585         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2586         return;
2587     } 
2588     
2589     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2590     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2591         marginStart = valueForLength(marginStartLength, containerWidth);
2592         marginEnd = containerWidth - childWidth - marginStart;
2593         return;
2594     } 
2595     
2596     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2597     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2598         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2599     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2600         marginEnd = valueForLength(marginEndLength, containerWidth);
2601         marginStart = containerWidth - childWidth - marginEnd;
2602         return;
2603     } 
2604     
2605     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2606     // auto margins will just turn into 0.
2607     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2608     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2609 }
2610
2611 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2612 {
2613     // Make sure nobody is trying to call this with a null region.
2614     if (!region)
2615         return nullptr;
2616
2617     // If we have computed our width in this region already, it will be cached, and we can
2618     // just return it.
2619     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2620     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2621         return boxInfo;
2622
2623     // No cached value was found, so we have to compute our insets in this region.
2624     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2625     // support to cover all boxes.
2626     RenderFlowThread* flowThread = flowThreadContainingBlock();
2627     if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2628         return nullptr;
2629
2630     LogicalExtentComputedValues computedValues;
2631     computeLogicalWidthInRegion(computedValues, region);
2632
2633     // Now determine the insets based off where this object is supposed to be positioned.
2634     RenderBlock* cb = containingBlock();
2635     RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2636     RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2637     LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2638     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2639     
2640     LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2641     LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2642     LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2643     LayoutUnit logicalLeftInRegion = computedValues.m_position;
2644     LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2645     LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2646     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2647     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2648     LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2649
2650     LayoutUnit logicalLeftOffset = 0;
2651     
2652     if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2653         LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2654         if (cb->style().isLeftToRightDirection())
2655             logicalLeftDelta += startPositionDelta;
2656         else
2657             logicalRightDelta += startPositionDelta;
2658     }
2659
2660     if (cb->style().isLeftToRightDirection())
2661         logicalLeftOffset += logicalLeftDelta;
2662     else
2663         logicalLeftOffset -= (widthDelta + logicalRightDelta);
2664     
2665     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2666     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2667             || (style().isLeftToRightDirection() && logicalLeftOffset)
2668             || (!style().isLeftToRightDirection() && logicalRightOffset);
2669
2670     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2671     if (cacheFlag == CacheRenderBoxRegionInfo)
2672         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2673     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2674 }
2675
2676 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2677 {
2678     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2679     WritingMode childWritingMode = childStyle->writingMode();
2680     bool shouldFlip = false;
2681     switch (containingBlockStyle.writingMode()) {
2682     case TopToBottomWritingMode:
2683         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2684         break;
2685     case BottomToTopWritingMode:
2686         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2687         break;
2688     case RightToLeftWritingMode:
2689         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2690         break;
2691     case LeftToRightWritingMode:
2692         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2693         break;
2694     }
2695
2696     if (!containingBlockStyle.isLeftToRightDirection())
2697         shouldFlip = !shouldFlip;
2698
2699     return shouldFlip;
2700 }
2701
2702 void RenderBox::updateLogicalHeight()
2703 {
2704     LogicalExtentComputedValues computedValues;
2705     computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2706
2707     setLogicalHeight(computedValues.m_extent);
2708     setLogicalTop(computedValues.m_position);
2709     setMarginBefore(computedValues.m_margins.m_before);
2710     setMarginAfter(computedValues.m_margins.m_after);
2711 }
2712
2713 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2714 {
2715     computedValues.m_extent = logicalHeight;
2716     computedValues.m_position = logicalTop;
2717
2718     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2719     if (isTableCell() || (isInline() && !isReplaced()))
2720         return;
2721
2722     Length h;
2723     if (isOutOfFlowPositioned())
2724         computePositionedLogicalHeight(computedValues);
2725     else {
2726         RenderBlock* cb = containingBlock();
2727         bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2728     
2729         if (!hasPerpendicularContainingBlock) {
2730             bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode();
2731             computeBlockDirectionMargins(cb,
2732                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2733                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2734         }
2735
2736         // For tables, calculate margins only.
2737         if (isTable()) {
2738             if (hasPerpendicularContainingBlock) {
2739                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2740                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2741                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2742                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2743             }
2744             return;
2745         }
2746
2747         // FIXME: Account for block-flow in flexible boxes.
2748         // https://bugs.webkit.org/show_bug.cgi?id=46418
2749         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2750         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2751         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2752         bool checkMinMaxHeight = false;
2753
2754         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2755         // grab our cached flexible height.
2756         // FIXME: Account for block-flow in flexible boxes.
2757         // https://bugs.webkit.org/show_bug.cgi?id=46418
2758         if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated()
2759 #if ENABLE(CSS_GRID_LAYOUT)
2760             || parent()->isRenderGrid()
2761 #endif
2762         ))
2763             h = Length(overrideLogicalContentHeight(), Fixed);
2764         else if (treatAsReplaced)
2765             h = Length(computeReplacedLogicalHeight(), Fixed);
2766         else {
2767             h = style().logicalHeight();
2768             checkMinMaxHeight = true;
2769         }
2770
2771         // Block children of horizontal flexible boxes fill the height of the box.
2772         // FIXME: Account for block-flow in flexible boxes.
2773         // https://bugs.webkit.org/show_bug.cgi?id=46418
2774         if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2775                 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2776             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2777             checkMinMaxHeight = false;
2778         }
2779
2780         LayoutUnit heightResult;
2781         if (checkMinMaxHeight) {
2782             LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2783             heightResult = computeLogicalHeightUsing(style().logicalHeight(), intrinsicHeight).valueOr(computedValues.m_extent);
2784             heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2785         } else {
2786             // The only times we don't check min/max height are when a fixed length has
2787             // been given as an override.  Just use that.  The value has already been adjusted
2788             // for box-sizing.
2789             ASSERT(h.isFixed());
2790             heightResult = h.value() + borderAndPaddingLogicalHeight();
2791         }
2792
2793         computedValues.m_extent = heightResult;
2794
2795         if (hasPerpendicularContainingBlock) {
2796             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2797             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2798                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2799                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2800         }
2801     }
2802
2803     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2804     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2805     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2806     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2807     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2808     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2809         && (isRoot() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2810     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2811         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2812         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2813         if (isRoot())
2814             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2815         else {
2816             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2817             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2818         }
2819     }
2820 }
2821
2822 Optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2823 {
2824     if (Optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight))
2825         return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2826     return Nullopt;
2827 }
2828
2829 Optional<LayoutUnit> RenderBox::computeContentLogicalHeight(const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2830 {
2831     if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight))
2832         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2833     return Nullopt;
2834 }
2835
2836 Optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, Optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2837 {
2838     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2839     // If that happens, this code will have to change.
2840     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent())
2841         return intrinsicContentHeight;
2842     if (logicalHeightLength.isFillAvailable())
2843         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2844     ASSERT_NOT_REACHED();
2845     return LayoutUnit(0);
2846 }
2847
2848 Optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2849 {
2850     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2851     // If that happens, this code will have to change.
2852     if (height.isIntrinsic())
2853         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2854     if (height.isFixed())
2855         return LayoutUnit(height.value());
2856     if (height.isPercentOrCalculated())
2857         return computePercentageLogicalHeight(height);
2858     return Nullopt;
2859 }
2860
2861 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock, bool isPerpendicularWritingMode) const
2862 {
2863     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2864     // and percent heights of children should be resolved against the multicol or paged container.
2865     if (containingBlock->isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2866         return true;
2867
2868     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2869     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2870     if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2871         return false;
2872     return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2873 }
2874
2875 Optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
2876 {
2877     Optional<LayoutUnit> availableHeight;
2878     
2879     bool skippedAutoHeightContainingBlock = false;
2880     RenderBlock* cb = containingBlock();
2881     const RenderBox* containingBlockChild = this;
2882     LayoutUnit rootMarginBorderPaddingHeight = 0;
2883     bool isHorizontal = isHorizontalWritingMode();
2884     while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb, isHorizontal != cb->isHorizontalWritingMode())) {
2885         if (cb->isBody() || cb->isRoot())
2886             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2887         skippedAutoHeightContainingBlock = true;
2888         containingBlockChild = cb;
2889         cb = cb->containingBlock();
2890         cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2891     }
2892
2893     const RenderStyle& cbstyle = cb->style();
2894
2895     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2896     // explicitly specified that can be used for any percentage computations.
2897     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2898
2899     bool includeBorderPadding = isTable();
2900
2901     if (isHorizontal != cb->isHorizontalWritingMode())
2902         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2903 #if ENABLE(CSS_GRID_LAYOUT)
2904     else if (hasOverrideContainingBlockLogicalHeight())
2905         availableHeight = overrideContainingBlockContentLogicalHeight();
2906 #endif
2907     else if (is<RenderTableCell>(*cb)) {
2908         if (!skippedAutoHeightContainingBlock) {
2909             // Table cells violate what the CSS spec says to do with heights. Basically we
2910             // don't care if the cell specified a height or not. We just always make ourselves
2911             // be a percentage of the cell's current content height.
2912             if (!cb->hasOverrideLogicalContentHeight()) {
2913                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2914                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2915                 // While we can't get all cases right, we can at least detect when the cell has a specified
2916                 // height or when the table has a specified height. In these cases we want to initially have
2917                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2918                 // to grow to fill the space. This could end up being wrong in some cases, but it is
2919                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2920                 RenderTableCell& cell = downcast<RenderTableCell>(*cb);
2921                 if (scrollsOverflowY() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto()))
2922                     return LayoutUnit(0);
2923                 return Nullopt;
2924             }
2925             availableHeight = cb->overrideLogicalContentHeight();
2926             includeBorderPadding = true;
2927         }
2928     } else if (cbstyle.logicalHeight().isFixed()) {
2929         LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(cbstyle.logicalHeight().value()));
2930         availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), Nullopt));
2931     } else if (cbstyle.logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2932         // We need to recur and compute the percentage height for our containing block.
2933         if (Optional<LayoutUnit> heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight())) {
2934             LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2935             // We need to adjust for min/max height because this method does not
2936             // handle the min/max of the current block, its caller does. So the
2937             // return value from the recursive call will not have been adjusted
2938             // yet.
2939             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), Nullopt);
2940             availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2941         }
2942     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2943         // Don't allow this to affect the block' height() member variable, since this
2944         // can get called while the block is still laying out its kids.
2945         LogicalExtentComputedValues computedValues;
2946         cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2947         availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2948     } else if (cb->isRenderView())
2949         availableHeight = view().pageOrViewLogicalHeight();
2950
2951     if (!availableHeight)
2952         return availableHeight;
2953
2954     LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight);
2955     if (includeBorderPadding) {
2956         // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2957         // It is necessary to use the border-box to match WinIE's broken
2958         // box model. This is essential for sizing inside
2959         // table cells using percentage heights.
2960         result -= borderAndPaddingLogicalHeight();
2961         return std::max<LayoutUnit>(0, result);
2962     }
2963     return result;
2964 }
2965
2966 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2967 {
2968     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style().logicalWidth()), shouldComputePreferred);
2969 }
2970
2971 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2972 {
2973     LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercentOrCalculated()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMinWidth());
2974     LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercentOrCalculated()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMaxWidth());
2975     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2976 }
2977
2978 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2979 {
2980     switch (logicalWidth.type()) {
2981         case Fixed:
2982             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2983         case MinContent:
2984         case MaxContent: {
2985             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2986             LayoutUnit availableLogicalWidth = 0;
2987             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2988         }
2989         case FitContent:
2990         case FillAvailable:
2991         case Percent: 
2992         case Calculated: {
2993             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2994             // containing block's block-flow.
2995             // https://bugs.webkit.org/show_bug.cgi?id=46496
2996             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(container())) : containingBlockLogicalWidthForContent();
2997             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2998             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2999             // https://bugs.webkit.org/show_bug.cgi?id=91071
3000             if (logicalWidth.isIntrinsic())
3001                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3002             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
3003                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
3004         }
3005         FALLTHROUGH;
3006         case Intrinsic:
3007         case MinIntrinsic:
3008         case Auto:
3009         case Relative:
3010         case Undefined:
3011             return intrinsicLogicalWidth();
3012     }
3013
3014     ASSERT_NOT_REACHED();
3015     return 0;
3016 }
3017
3018 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
3019 {
3020     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style().logicalHeight()));
3021 }
3022
3023 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3024 {
3025     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style().logicalMinHeight());
3026     LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style().logicalMaxHeight());
3027     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3028 }
3029
3030 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
3031 {
3032     switch (logicalHeight.type()) {
3033         case Fixed:
3034             return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3035         case Percent:
3036         case Calculated:
3037         {
3038             auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
3039             while (cb->isAnonymous() && !is<RenderView>(*cb)) {
3040                 cb = cb->containingBlock();
3041                 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3042             }
3043
3044             // FIXME: This calculation is not patched for block-flow yet.
3045             // https://bugs.webkit.org/show_bug.cgi?id=46500
3046             if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
3047                 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
3048                 RenderBlock& block = downcast<RenderBlock>(*cb);
3049                 LogicalExtentComputedValues computedValues;
3050                 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3051                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3052                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3053                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3054             }
3055             
3056             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3057             // containing block's block-flow.
3058             // https://bugs.webkit.org/show_bug.cgi?id=46496
3059             LayoutUnit availableHeight;
3060             if (isOutOfFlowPositioned())
3061                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(cb));
3062             else {
3063                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3064                 // It is necessary to use the border-box to match WinIE's broken
3065                 // box model.  This is essential for sizing inside
3066                 // table cells using percentage heights.
3067                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3068                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3069                 while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercentOrCalculated())) {
3070                     if (cb->isTableCell()) {
3071                         // Don't let table cells squeeze percent-height replaced elements
3072                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3073                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3074                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3075                     }
3076                     downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3077                     cb = cb->containingBlock();
3078                 }
3079             }
3080             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3081         }
3082         case MinContent:
3083         case MaxContent:
3084         case FitContent:
3085         case FillAvailable:
3086             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3087         default:
3088             return intrinsicLogicalHeight();
3089     }
3090 }
3091
3092 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3093 {
3094     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), Nullopt);
3095 }
3096
3097 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3098 {
3099     // We need to stop here, since we don't want to increase the height of the table
3100     // artificially.  We're going to rely on this cell getting expanded to some new
3101     // height, and then when we lay out again we'll use the calculation below.
3102     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3103         if (hasOverrideLogicalContentHeight())
3104             return overrideLogicalContentHeight();
3105         return logicalHeight() - borderAndPaddingLogicalHeight();
3106     }
3107
3108     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3109         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3110         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
3111         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3112     }
3113
3114     if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h, Nullopt))
3115         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3116
3117     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3118     // https://bugs.webkit.org/show_bug.cgi?id=46500
3119     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3120         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3121         LogicalExtentComputedValues computedValues;
3122         block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3123         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3124         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3125     }
3126
3127     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3128     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3129     if (heightType == ExcludeMarginBorderPadding) {
3130         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3131         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3132     }
3133     return availableHeight;
3134 }
3135
3136 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3137 {
3138     if (isTableCell()) {
3139         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3140         // we may just do it with an extra anonymous block inside the cell.
3141         marginBefore = 0;
3142         marginAfter = 0;
3143         return;
3144     }
3145
3146     // Margins are calculated with respect to the logical width of
3147     // the containing block (8.3)
3148     LayoutUnit cw = containingBlockLogicalWidthForContent();
3149     const RenderStyle& containingBlockStyle = containingBlock->style();
3150     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3151     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3152 }
3153
3154 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
3155 {
3156     LayoutUnit marginBefore;
3157     LayoutUnit marginAfter;
3158     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3159     containingBlock->setMarginBeforeForChild(*this, marginBefore);
3160     containingBlock->setMarginAfterForChild(*this, marginAfter);
3161 }
3162
3163 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3164 {
3165     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3166         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3167
3168     if (is<RenderBox>(*containingBlock)) {
3169         bool isFixedPosition = style().position() == FixedPosition;
3170
3171         RenderFlowThread* flowThread = flowThreadContainingBlock();
3172         if (!flowThread) {
3173             if (isFixedPosition && is<RenderView>(*containingBlock))
3174                 return downcast<RenderView>(*containingBlock).clientLogicalWidthForFixedPosition();
3175
3176             return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3177         }
3178
3179         if (isFixedPosition && is<RenderNamedFlowThread>(*containingBlock))
3180             return containingBlock->view().clientLogicalWidth();
3181
3182         if (!is<RenderBlock>(*containingBlock))
3183             return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3184
3185         const RenderBlock& cb = downcast<RenderBlock>(*containingBlock);
3186         RenderBoxRegionInfo* boxInfo = nullptr;
3187         if (!region) {
3188             if (is<RenderFlowThread>(*containingBlock) && !checkForPerpendicularWritingMode)
3189                 return downcast<RenderFlowThread>(*containingBlock).contentLogicalWidthOfFirstRegion();
3190             if (isWritingModeRoot()) {
3191                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3192                 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3193                 if (cbRegion)
3194                     boxInfo = cb.renderBoxRegionInfo(cbRegion);
3195             }
3196         } else if (flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3197             RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3198             boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3199         }
3200         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3201     }
3202
3203     ASSERT(containingBlock->isInFlowPositioned());
3204
3205     const auto& flow = downcast<RenderInline>(*containingBlock);
3206     InlineFlowBox* first = flow.firstLineBox();
3207     InlineFlowBox* last = flow.lastLineBox();
3208
3209     // If the containing block is empty, return a width of 0.
3210     if (!first || !last)
3211         return 0;
3212
3213     LayoutUnit fromLeft;
3214     LayoutUnit fromRight;
3215     if (containingBlock->style().isLeftToRightDirection()) {
3216         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3217         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3218     } else {
3219         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3220         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3221     }
3222
3223     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3224 }
3225
3226 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3227 {
3228     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3229         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3230
3231     if (containingBlock->isBox()) {
3232         bool isFixedPosition = style().position() == FixedPosition;
3233
3234         if (isFixedPosition && is<RenderView>(*containingBlock))
3235             return downcast<RenderView>(*containingBlock).clientLogicalHeightForFixedPosition();
3236
3237         const RenderBlock* cb = is<RenderBlock>(*containingBlock) ? downcast<RenderBlock>(containingBlock) : containingBlock->containingBlock();
3238         LayoutUnit result = cb->clientLogicalHeight();
3239         RenderFlowThread* flowThread = flowThreadContainingBlock();
3240         if (flowThread && is<RenderFlowThread>(*containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3241             if (is<RenderNamedFlowThread>(*containingBlock) && isFixedPosition)
3242                 return containingBlock->view().clientLogicalHeight();
3243             return downcast<RenderFlowThread>(*containingBlock).contentLogicalHeightOfFirstRegion();
3244         }
3245         return result;
3246     }
3247         
3248     ASSERT(containingBlock->isInFlowPositioned());
3249
3250     const auto& flow = downcast<RenderInline>(*containingBlock);
3251     InlineFlowBox* first = flow.firstLineBox();
3252     InlineFlowBox* last = flow.lastLineBox();
3253
3254     // If the containing block is empty, return a height of 0.
3255     if (!first || !last)
3256         return 0;
3257
3258     LayoutUnit heightResult;
3259     LayoutRect boundingBox = flow.linesBoundingBox();
3260     if (containingBlock->isHorizontalWritingMode())
3261         heightResult = boundingBox.height();
3262     else
3263         heightResult = boundingBox.width();
3264     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3265     return heightResult;
3266 }
3267
3268 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3269 {
3270     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3271         return;
3272
3273     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3274     if (child->parent()->style().direction() == LTR) {
3275         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3276         for (auto current = child->parent(); current && current != containerBlock; current = current->container()) {
3277             if (is<RenderBox>(*current)) {
3278                 staticPosition += downcast<RenderBox>(*current).logicalLeft();
3279                 if (region && is<RenderBlock>(*current)) {
3280                     const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3281                     region = currentBlock.clampToStartAndEndRegions(region);
3282                     RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3283                     if (boxInfo)
3284                         staticPosition += boxInfo->logicalLeft();
3285                 }
3286             }
3287         }
3288         logicalLeft.setValue(Fixed, staticPosition);
3289     } else {
3290         RenderBox& enclosingBox = child->parent()->enclosingBox();
3291         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3292         for (RenderElement* current = &enclosingBox; current; current = current->container()) {
3293             if (is<RenderBox>(*current)) {
3294                 if (current != containerBlock)
3295                     staticPosition -= downcast<RenderBox>(*current).logicalLeft();
3296                 if (current == &enclosingBox)
3297                     staticPosition -= enclosingBox.logicalWidth();
3298                 if (region && is<RenderBlock>(*current)) {
3299                     const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3300                     region = currentBlock.clampToStartAndEndRegions(region);
3301                     RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3302                     if (boxInfo) {
3303                         if (current != containerBlock)
3304                             staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3305                         if (current == &enclosingBox)
3306                             staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3307                     }
3308                 }
3309             }
3310             if (current == containerBlock)
3311                 break;
3312         }
3313         logicalRight.setValue(Fixed, staticPosition);
3314     }
3315 }
3316
3317 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3318 {
3319     if (isReplaced()) {
3320         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3321         // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3322         computePositionedLogicalWidthReplaced(computedValues);
3323         return;
3324     }
3325
3326     // QUESTIONS
3327     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3328     // the type 'static' in determining whether to calculate the static distance?
3329     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3330
3331     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3332     // than or less than the computed width().  Be careful of box-sizing and
3333     // percentage issues.
3334
3335     // The following is based off of the W3C Working Draft from April 11, 2006 of
3336     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3337     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3338     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3339     // correspond to text from the spec)
3340
3341
3342     // We don't use containingBlock(), since we may be positioned by an enclosing
3343     // relative positioned inline.
3344     const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3345     
3346     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3347
3348     // Use the container block's direction except when calculating the static distance
3349     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3350     // of the CSS 2.1 test suite
3351     TextDirection containerDirection = containerBlock->style().direction();
3352
3353     bool isHorizontal = isHorizontalWritingMode();
3354     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3355     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3356     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3357
3358     Length logicalLeftLength = style().logicalLeft();
3359     Length logicalRightLength = style().logicalRight();
3360
3361     /*---------------------------------------------------------------------------*\
3362      * For the purposes of this section and the next, the term "static position"
3363      * (of an element) refers, roughly, to the position an element would have had
3364      * in the normal flow. More precisely:
3365      *
3366      * * The static position for 'left' is the distance from the left edge of the
3367      *   containing block to the left margin edge of a hypothetical box that would
3368      *   have been the first box of the element if its 'position' property had
3369      *   been 'static' and 'float' had been 'none'. The value is negative if the
3370      *   hypothetical box is to the left of the containing block.
3371      * * The static position for 'right' is the distance from the right edge of the
3372      *   containing block to the right margin edge of the same hypothetical box as
3373      *   above. The value is positive if the hypothetical box is to the left of the
3374      *   containing block's edge.
3375      *
3376      * But rather than actually calculating the dimensions of that hypothetical box,
3377      * user agents are free to make a guess at its probable position.
3378      *
3379      * For the purposes of calculating the static position, the containing block of
3380      * fixed positioned elements is the initial containing block instead of the
3381      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3382      * origin.
3383     \*---------------------------------------------------------------------------*/
3384
3385     // see FIXME 1
3386     // Calculate the static distance if needed.
3387     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3388     
3389     // Calculate constraint equation values for 'width' case.
3390     computePositionedLogicalWidthUsing(style().logicalWidth(), containerBlock, containerDirection,
3391                                        containerLogicalWidth, bordersPlusPadding,
3392                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3393                                        computedValues);
3394
3395     // Calculate constraint equation values for 'max-width' case.
3396     if (!style().logicalMaxWidth().isUndefined()) {
3397         LogicalExtentComputedValues maxValues;
3398
3399         computePositionedLogicalWidthUsing(style().logicalMaxWidth(), containerBlock, containerDirection,
3400                                            containerLogicalWidth, bordersPlusPadding,
3401                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3402                                            maxValues);
3403
3404         if (computedValues.m_extent > maxValues.m_extent) {
3405             computedValues.m_extent = maxValues.m_extent;
3406             computedValues.m_position = maxValues.m_position;
3407             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3408             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3409         }
3410     }
3411
3412     // Calculate constraint equation values for 'min-width' case.
3413     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3414         LogicalExtentComputedValues minValues;
3415
3416         computePositionedLogicalWidthUsing(style().logicalMinWidth(), containerBlock, containerDirection,
3417                                            containerLogicalWidth, bordersPlusPadding,
3418                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3419                                            minValues);
3420
3421         if (computedValues.m_extent < minValues.m_extent) {
3422             computedValues.m_extent = minValues.m_extent;
3423             computedValues.m_position = minValues.m_position;
3424             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3425             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3426         }
3427     }
3428
3429     computedValues.m_extent += bordersPlusPadding;
3430     
3431     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3432     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3433     RenderFlowThread* flowThread = flowThreadContainingBlock();
3434     if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3435         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3436         LayoutUnit logicalLeftPos = computedValues.m_position;
3437         const RenderBlock& renderBlock = downcast<RenderBlock>(*containerBlock);
3438         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3439         RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3440         if (cbRegion) {
3441             RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3442             if (boxInfo) {
3443                 logicalLeftPos += boxInfo->logicalLeft();
3444                 computedValues.m_position = logicalLeftPos;
3445             }
3446         }
3447     }
3448 }
3449
3450 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
3451 {
3452     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3453     // 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.
3454     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style().isFlippedBlocksWritingMode()) {
3455         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3456         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
3457     } else
3458         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
3459 }
3460
3461 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
3462                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3463                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3464                                                    LogicalExtentComputedValues& computedValues) const
3465 {
3466     if (logicalWidth.isIntrinsic())
3467         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3468
3469     // 'left' and 'right' cannot both be 'auto' because one would of been
3470     // converted to the static position already
3471     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3472
3473     LayoutUnit logicalLeftValue = 0;
3474
3475     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3476
3477     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3478     bool logicalLeftIsAuto = logicalLeft.isAuto();
3479     bool logicalRightIsAuto = logicalRight.isAuto();
3480     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3481     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3482
3483     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3484         /*-----------------------------------------------------------------------*\
3485          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3486          * right' are 'auto', solve the equation under the extra constraint that
3487          * the two margins get equal values, unless this would make them negative,
3488          * in which case when direction of the containing block is 'ltr' ('rtl'),
3489          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3490          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3491          * solve the equation for that value. If the values are over-constrained,
3492          * ignore the value for 'left' (in case the 'direction' property of the
3493          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3494          * and solve for that value.
3495         \*-----------------------------------------------------------------------*/
3496         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3497         // case because the value is not used for any further calculations.
3498
3499         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3500         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3501
3502         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3503
3504         // Margins are now the only unknown
3505         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3506             // Both margins auto, solve for equality
3507             if (availableSpace >= 0) {
3508                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3509                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3510             } else {
3511                 // Use the containing block's direction rather than the parent block's
3512                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3513                 if (containerDirection == LTR) {
3514                     marginLogicalLeftValue = 0;
3515                     marginLogicalRightValue = availableSpace; // will be negative
3516                 } else {
3517                     marginLogicalLeftValue = availableSpace; // will be negative
3518                     marginLogicalRightValue = 0;
3519                 }
3520             }
3521         } else if (marginLogicalLeft.isAuto()) {
3522             // Solve for left margin
3523             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3524             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3525         } else if (marginLogicalRight.isAuto()) {
3526             // Solve for right margin
3527             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3528             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3529         } else {
3530             // Over-constrained, solve for left if direction is RTL
3531             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3532             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3533
3534             // Use the containing block's direction rather than the parent block's
3535             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3536             if (containerDirection == RTL)
3537                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3538         }
3539     } else {
3540         /*--------------------------------------------------------------------*\
3541          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3542          * to 0, and pick the one of the following six rules that applies.
3543          *
3544          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3545          *    width is shrink-to-fit. Then solve for 'left'
3546          *
3547          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3548          * ------------------------------------------------------------------
3549          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3550          *    the 'direction' property of the containing block is 'ltr' set
3551          *    'left' to the static position, otherwise set 'right' to the
3552          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3553          *    or 'right' (if 'direction' is 'ltr').
3554          * ------------------------------------------------------------------
3555          *
3556          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3557          *    width is shrink-to-fit . Then solve for 'right'
3558          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3559          *    for 'left'
3560          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3561          *    for 'width'
3562          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3563          *    for 'right'
3564          *
3565          * Calculation of the shrink-to-fit width is similar to calculating the
3566          * width of a table cell using the automatic table layout algorithm.
3567          * Roughly: calculate the preferred width by formatting the content
3568          * without breaking lines other than where explicit line breaks occur,
3569          * and also calculate the preferred minimum width, e.g., by trying all
3570          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3571          * Thirdly, calculate the available width: this is found by solving
3572          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3573          * to 0.
3574          *
3575          * Then the shrink-to-fit width is:
3576          * min(max(preferred minimum width, available width), preferred width).
3577         \*--------------------------------------------------------------------*/
3578         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3579         // because the value is not used for any further calculations.
3580
3581         // Calculate margins, 'auto' margins are ignored.
3582         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3583         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3584
3585         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3586
3587         // FIXME: Is there a faster way to find the correct case?
3588         // Use rule/case that applies.
3589         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3590             // RULE 1: (use shrink-to-fit for width, and solve of left)
3591             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3592
3593             // FIXME: would it be better to have shrink-to-fit in one step?
3594             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3595             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3596             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3597             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3598             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3599         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3600             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3601             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3602
3603             // FIXME: would it be better to have shrink-to-fit in one step?
3604             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3605             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3606             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3607             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3608         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3609             // RULE 4: (solve for left)
3610             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3611             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3612         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3613             // RULE 5: (solve for width)
3614             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3615             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3616         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3617             // RULE 6: (no need solve for right)
3618             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3619             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3620         }
3621     }
3622
3623     // Use computed values to calculate the horizontal position.
3624
3625     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3626     // positioned, inline because right now, it is using the logical left position
3627     // of the first line box when really it should use the last line box.  When
3628     // this is fixed elsewhere, this block should be removed.
3629     if (is<RenderInline>(*containerBlock) && !containerBlock->style().isLeftToRightDirection()) {
3630         const auto& flow = downcast<RenderInline>(*containerBlock);
3631         InlineFlowBox* firstLine = flow.firstLineBox();
3632         InlineFlowBox* lastLine = flow.lastLineBox();
3633         if (firstLine && lastLine && firstLine != lastLine) {
3634             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3635             return;
3636         }
3637     }
3638
3639     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3640     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3641 }
3642
3643 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3644 {
3645     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3646         return;
3647     
3648     // FIXME: The static distance computation has not been patched for mixed writing modes.
3649     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3650     for (RenderElement* container = child->parent(); container && container != containerBlock; container = container->container()) {
3651         if (is<RenderBox>(*container) && !is<RenderTableRow>(*container))
3652             staticLogicalTop += downcast<RenderBox>(*container).logicalTop();
3653     }
3654     logicalTop.setValue(Fixed, staticLogicalTop);
3655 }
3656
3657 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3658 {
3659     if (isReplaced()) {
3660         computePositionedLogicalHeightReplaced(computedValues);
3661         return;
3662     }
3663
3664     // The following is based off of the W3C Working Draft from April 11, 2006 of
3665     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3666     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3667     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3668     // correspond to text from the spec)
3669
3670
3671     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3672     const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3673
3674     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3675
3676     const RenderStyle& styleToUse = style();
3677     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3678     const Length marginBefore = styleToUse.marginBefore();
3679     const Length marginAfter = styleToUse.marginAfter();
3680     Length logicalTopLength = styleToUse.logicalTop();
3681     Length logicalBottomLength = styleToUse.logicalBottom();
3682
3683     /*---------------------------------------------------------------------------*\
3684      * For the purposes of this section and the next, the term "static position"
3685      * (of an element) refers, roughly, to the position an element would have had
3686      * in the normal flow. More precisely, the static position for 'top' is the
3687      * distance from the top edge of the containing block to the top margin edge
3688      * of a hypothetical box that would have been the first box of the element if
3689      * its 'position' property had been 'static' and 'float' had been 'none'. The
3690      * value is negative if the hypothetical box is above the containing block.
3691      *
3692      * But rather than actually calculating the dimensions of that hypothetical
3693      * box, user agents are free to make a guess at its probable position.
3694      *
3695      * For the purposes of calculating the static position, the containing block
3696      * of fixed positioned elements is the initial containing block instead of
3697      * the viewport.
3698     \*---------------------------------------------------------------------------*/
3699
3700     // see FIXME 1
3701     // Calculate the static distance if needed.
3702     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3703
3704     // Calculate constraint equation values for 'height' case.
3705     LayoutUnit logicalHeight = computedValues.m_extent;
3706     computePositionedLogicalHeightUsing(styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3707                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3708                                         computedValues);
3709
3710     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3711     // see FIXME 2
3712
3713     // Calculate constraint equation values for 'max-height' case.
3714     if (!styleToUse.logicalMaxHeight().isUndefined()) {
3715         LogicalExtentComputedValues maxValues;
3716
3717         computePositionedLogicalHeightUsing(styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3718                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3719                                             maxValues);
3720
3721         if (computedValues.m_extent > maxValues.m_extent) {
3722             computedValues.m_extent = maxValues.m_extent;
3723             computedValues.m_position = maxValues.m_position;
3724             computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3725             computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3726         }
3727     }
3728
3729     // Calculate constraint equation values for 'min-height' case.
3730     if (!styleToUse.logicalMinHeight().isZero() || styleToUse.logicalMinHeight().isIntrinsic()) {
3731         LogicalExtentComputedValues minValues;
3732
3733         computePositionedLogicalHeightUsing(styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3734                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3735                                             minValues);
3736
3737         if (computedValues.m_extent < minValues.m_extent) {
3738             computedValues.m_extent = minValues.m_extent;
3739             computedValues.m_position = minValues.m_position;
3740             computedValues.m_margins.m_before = minValues.m_margins.m_before;
3741             computedValues.m_margins.m_after = minValues.m_margins.m_after;
3742         }
3743     }
3744
3745     // Set final height value.
3746     computedValues.m_extent += bordersPlusPadding;
3747     
3748     // Adjust logicalTop if we need to for perpendicular writing modes in regions.
3749     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3750     RenderFlowThread* flowThread = flowThreadContainingBlock();
3751     if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3752         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3753         LayoutUnit logicalTopPos = computedValues.m_position;
3754         const RenderBlock& renderBox = downcast<RenderBlock>(*containerBlock);
3755         LayoutUnit cbPageOffset = renderBox.offsetFromLogicalTopOfFirstPage() - logicalLeft();
3756         RenderRegion* cbRegion = renderBox.regionAtBlockOffset(cbPageOffset);
3757         if (cbRegion) {
3758             RenderBoxRegionInfo* boxInfo = renderBox.renderBoxRegionInfo(cbRegion);
3759             if (boxInfo) {
3760                 logicalTopPos += boxInfo->logicalLeft();
3761                 computedValues.m_position = logicalTopPos;
3762             }
3763         }
3764     }
3765 }
3766
3767 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3768 {
3769     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3770     // 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.
3771     if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3772         || (child->style().isFlippedBlocksWritingMode() != containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3773         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3774
3775     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3776     if (containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3777         if (child->isHorizontalWritingMode())
3778             logicalTopPos += containerBlock->borderBottom();
3779         else
3780             logicalTopPos += containerBlock->borderRight();
3781     } else {
3782         if (child->isHorizontalWritingMode())
3783             logicalTopPos += containerBlock->borderTop();
3784         else
3785             logicalTopPos += containerBlock->borderLeft();
3786     }
3787 }
3788
3789 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3790                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3791                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,