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