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