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