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