25eb8c2d867d3d77a4d4eef6e98948d8e2270109
[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 && (isDocumentElementRenderer() || 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() && layer() && 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 isDocElementRenderer = isDocumentElementRenderer();
377
378     // Set the text color if we're the body.
379     if (isBodyRenderer)
380         document().setTextColor(newStyle.visitedDependentColor(CSSPropertyColor));
381
382     if (isDocElementRenderer || 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() && (isDocElementRenderer || !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() && (isDocElementRenderer || !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 isDocElementRenderer = isDocumentElementRenderer();
481     bool isViewObject = isRenderView();
482
483     // The root and the RenderView always paint their backgrounds/borders.
484     if (isDocElementRenderer || 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 && !isDocElementRenderer && 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() && layer())
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() && layer())
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() ? layer()->scrollXOffset() : 0;
579 }
580
581 int RenderBox::scrollTop() const
582 {
583     return hasOverflowClip() && layer() ? 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() || !layer())
601         return;
602     setupWheelEventTestTrigger(*layer(), document().frame());
603     layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
604 }
605
606 void RenderBox::setScrollTop(int newTop)
607 {
608     if (!hasOverflowClip() || !layer())
609         return;
610     setupWheelEventTestTrigger(*layer(), document().frame());
611     layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
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(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
650             logicalHeight = std::min(logicalHeight, maxH.value());
651     }
652     if (Optional<LayoutUnit> computedLogicalHeight = computeLogicalHeightUsing(MinSize, 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(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
662             logicalHeight = std::min(logicalHeight, maxH.value());
663     }
664     if (Optional<LayoutUnit> computedContentLogicalHeight = computeContentLogicalHeight(MinSize, 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() && !layer()->hasOverlayScrollbars()
765         && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
766 }
767
768 bool RenderBox::includeHorizontalScrollbarSize() const
769 {
770     return hasOverflowClip() && layer() && !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() && layer()->hasVerticalScrollbar());
791         return verticalScrollbarWidth();
792     }
793
794     if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
795         ASSERT(layer() && 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 (isDocumentElementRenderer()) {
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() || isDocumentElementRenderer())
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 && (isDocumentElementRenderer() || (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     return computeRectForRepaint(r, repaintContainer);
2145 }
2146
2147 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2148 {
2149 #if PLATFORM(IOS)
2150     if (!repaintContainer || repaintContainer != containerBox)
2151         return true;
2152
2153     return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2154 #else
2155     UNUSED_PARAM(repaintContainer);
2156     UNUSED_PARAM(containerBox);
2157     return true;
2158 #endif
2159 }
2160
2161 LayoutRect RenderBox::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, bool fixed) const
2162 {
2163     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2164     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2165     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2166     // properly even during layout, since the rect remains flipped all the way until the end.
2167     //
2168     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2169     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2170     // physical coordinate space of the repaintContainer.
2171     LayoutRect adjustedRect = rect;
2172     const RenderStyle& styleToUse = style();
2173     // LayoutState is only valid for root-relative, non-fixed position repainting
2174     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2175         LayoutState* layoutState = view().layoutState();
2176
2177         if (layer() && layer()->transform())
2178             adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2179
2180         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2181         if (styleToUse.hasInFlowPosition() && layer())
2182             adjustedRect.move(layer()->offsetForInFlowPosition());
2183
2184         adjustedRect.moveBy(location());
2185         adjustedRect.move(layoutState->m_paintOffset);
2186         if (layoutState->m_clipped)
2187             adjustedRect.intersect(layoutState->m_clipRect);
2188         return adjustedRect;
2189     }
2190
2191     if (hasReflection())
2192         adjustedRect.unite(reflectedRect(adjustedRect));
2193
2194     if (repaintContainer == this) {
2195         if (repaintContainer->style().isFlippedBlocksWritingMode())
2196             flipForWritingMode(adjustedRect);
2197         return adjustedRect;
2198     }
2199
2200     bool containerSkipped;
2201     auto* renderer = container(repaintContainer, &containerSkipped);
2202     if (!renderer)
2203         return adjustedRect;
2204     
2205     EPosition position = styleToUse.position();
2206
2207     // This code isn't necessary for in-flow RenderFlowThreads.
2208     // Don't add the location of the region in the flow thread for absolute positioned
2209     // elements because their absolute position already pushes them down through
2210     // the regions so adding this here and then adding the topLeft again would cause
2211     // us to add the height twice.
2212     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2213     // will already contain the portion rect of the region.
2214     if (renderer->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2215         RenderRegion* firstRegion = nullptr;
2216         RenderRegion* lastRegion = nullptr;
2217         if (downcast<RenderFlowThread>(*renderer).getRegionRangeForBox(this, firstRegion, lastRegion))
2218             adjustedRect.moveBy(firstRegion->flowThreadPortionRect().location());
2219     }
2220
2221     if (isWritingModeRoot() && !isOutOfFlowPositioned())
2222         flipForWritingMode(adjustedRect);
2223
2224     LayoutSize locationOffset = this->locationOffset();
2225     // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2226     if (isRenderReplaced() && isWidget()) {
2227         LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2228         adjustedRect.expand(locationOffset - flooredLocationOffset);
2229         locationOffset = flooredLocationOffset;
2230     }
2231     LayoutPoint topLeft = adjustedRect.location();
2232     topLeft.move(locationOffset);
2233
2234     // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2235     // in the parent's coordinate space that encloses us.
2236     if (hasLayer() && layer()->transform()) {
2237         fixed = position == FixedPosition;
2238         adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2239         topLeft = adjustedRect.location();
2240         topLeft.move(locationOffset);
2241     } else if (position == FixedPosition)
2242         fixed = true;
2243
2244     if (position == AbsolutePosition && renderer->isInFlowPositioned() && is<RenderInline>(*renderer))
2245         topLeft += downcast<RenderInline>(*renderer).offsetForInFlowPositionedInline(this);
2246     else if (styleToUse.hasInFlowPosition() && layer()) {
2247         // Apply the relative position offset when invalidating a rectangle.  The layer
2248         // is translated, but the render box isn't, so we need to do this to get the
2249         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2250         // flag on the RenderObject has been cleared, so use the one on the style().
2251         topLeft += layer()->offsetForInFlowPosition();
2252     }
2253
2254     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2255     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2256     adjustedRect.setLocation(topLeft);
2257     if (renderer->hasOverflowClip()) {
2258         RenderBox& containerBox = downcast<RenderBox>(*renderer);
2259         if (shouldApplyContainersClipAndOffset(repaintContainer, &containerBox)) {
2260             containerBox.applyCachedClipAndScrollOffsetForRepaint(adjustedRect);
2261             if (adjustedRect.isEmpty())
2262                 return adjustedRect;
2263         }
2264     }
2265
2266     if (containerSkipped) {
2267         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2268         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*renderer);
2269         adjustedRect.move(-containerOffset);
2270         return adjustedRect;
2271     }
2272     return renderer->computeRectForRepaint(adjustedRect, repaintContainer, fixed);
2273 }
2274
2275 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2276 {
2277     if (oldRect.location() != m_frameRect.location()) {
2278         LayoutRect newRect = m_frameRect;
2279         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2280         // since the object may not have gotten a layout.
2281         m_frameRect = oldRect;
2282         repaint();
2283         repaintOverhangingFloats(true);
2284         m_frameRect = newRect;
2285         repaint();
2286         repaintOverhangingFloats(true);
2287     }
2288 }
2289
2290 void RenderBox::repaintOverhangingFloats(bool)
2291 {
2292 }
2293
2294 void RenderBox::updateLogicalWidth()
2295 {
2296     LogicalExtentComputedValues computedValues;
2297     computeLogicalWidthInRegion(computedValues);
2298
2299     setLogicalWidth(computedValues.m_extent);
2300     setLogicalLeft(computedValues.m_position);
2301     setMarginStart(computedValues.m_margins.m_start);
2302     setMarginEnd(computedValues.m_margins.m_end);
2303 }
2304
2305 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2306 {
2307     computedValues.m_extent = logicalWidth();
2308     computedValues.m_position = logicalLeft();
2309     computedValues.m_margins.m_start = marginStart();
2310     computedValues.m_margins.m_end = marginEnd();
2311
2312     if (isOutOfFlowPositioned()) {
2313         // FIXME: This calculation is not patched for block-flow yet.
2314         // https://bugs.webkit.org/show_bug.cgi?id=46500
2315         computePositionedLogicalWidth(computedValues, region);
2316         return;
2317     }
2318
2319     // If layout is limited to a subtree, the subtree root's logical width does not change.
2320     if (element() && !view().frameView().layoutPending() && view().frameView().layoutRoot() == this)
2321         return;
2322
2323     // The parent box is flexing us, so it has increased or decreased our
2324     // width.  Use the width from the style context.
2325     // FIXME: Account for block-flow in flexible boxes.
2326     // https://bugs.webkit.org/show_bug.cgi?id=46418
2327     if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()
2328 #if ENABLE(CSS_GRID_LAYOUT)
2329         || parent()->isRenderGrid()
2330 #endif
2331     ))) {
2332         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2333         return;
2334     }
2335
2336     // FIXME: Account for block-flow in flexible boxes.
2337     // https://bugs.webkit.org/show_bug.cgi?id=46418
2338     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2339     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2340     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2341
2342     const RenderStyle& styleToUse = style();
2343     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2344
2345     RenderBlock* cb = containingBlock();
2346     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2347     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2348
2349 #if ENABLE(CSS_GRID_LAYOUT)
2350     if (parent()->isRenderGrid() && style().logicalWidth().isAuto() && style().logicalMinWidth().isAuto() && style().overflowX() == OVISIBLE) {
2351         LayoutUnit minLogicalWidth = minPreferredLogicalWidth();
2352         if (containerLogicalWidth < minLogicalWidth) {
2353             computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(minLogicalWidth, containerLogicalWidth, cb);
2354             return;
2355         }
2356     }
2357 #endif
2358
2359     if (isInline() && !isInlineBlockOrInlineTable()) {
2360         // just calculate margins
2361         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2362         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2363         if (treatAsReplaced)
2364             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2365         return;
2366     }
2367
2368     // Width calculations
2369     if (treatAsReplaced)
2370         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2371     else {
2372         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2373         if (hasPerpendicularContainingBlock)
2374             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2375         LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2376         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2377     }
2378
2379     // Margin calculations.
2380     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2381         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2382         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2383     } else {
2384         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2385         if (avoidsFloats() && cb->containsFloats())
2386             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2387         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2388         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2389             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2390             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2391     }
2392     
2393     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2394         && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated()
2395 #if ENABLE(CSS_GRID_LAYOUT)
2396         && !cb->isRenderGrid()
2397 #endif
2398         ) {
2399         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
2400         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2401         if (hasInvertedDirection)
2402             computedValues.m_margins.m_start = newMargin;
2403         else
2404             computedValues.m_margins.m_end = newMargin;
2405     }
2406 }
2407
2408 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2409 {
2410     LayoutUnit marginStart = 0;
2411     LayoutUnit marginEnd = 0;
2412     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2413 }
2414
2415 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2416 {
2417     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2418     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2419     return availableLogicalWidth - marginStart - marginEnd;
2420 }
2421
2422 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2423 {
2424     if (logicalWidthLength.type() == FillAvailable)
2425         return fillAvailableMeasure(availableLogicalWidth);
2426
2427     LayoutUnit minLogicalWidth = 0;
2428     LayoutUnit maxLogicalWidth = 0;
2429     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2430
2431     if (logicalWidthLength.type() == MinContent)
2432         return minLogicalWidth + borderAndPadding;
2433
2434     if (logicalWidthLength.type() == MaxContent)
2435         return maxLogicalWidth + borderAndPadding;
2436
2437     if (logicalWidthLength.type() == FitContent) {
2438         minLogicalWidth += borderAndPadding;
2439         maxLogicalWidth += borderAndPadding;
2440         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2441     }
2442
2443     ASSERT_NOT_REACHED();
2444     return 0;
2445 }
2446
2447 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2448     const RenderBlock* cb, RenderRegion* region) const
2449 {
2450     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2451     if (widthType == MinSize && logicalWidth.isAuto())
2452         return adjustBorderBoxLogicalWidthForBoxSizing(0);
2453
2454     if (!logicalWidth.isIntrinsicOrAuto()) {
2455         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2456         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2457     }
2458
2459     if (logicalWidth.isIntrinsic())
2460         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2461
2462     LayoutUnit marginStart = 0;
2463     LayoutUnit marginEnd = 0;
2464     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2465
2466     if (shrinkToAvoidFloats() && cb->containsFloats())
2467         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2468
2469     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2470         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2471     return logicalWidthResult;
2472 }
2473
2474 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2475 {
2476     auto parent = flexitem.parent();
2477     return RenderStyle::resolveAlignment(parent->style(), flexitem.style(), ItemPositionStretch) == ItemPositionStretch;
2478 }
2479
2480 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2481 {
2482     auto parent = flexitem.parent();
2483     if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2484         return true;
2485
2486     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2487     if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2488         return true;
2489     return false;
2490 }
2491
2492 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2493 {
2494     // Anonymous inline blocks always fill the width of their containing block.
2495     if (isAnonymousInlineBlock())
2496         return false;
2497
2498     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2499     // but they allow text to sit on the same line as the marquee.
2500     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2501         return true;
2502
2503     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2504     // min-width and width.  max-width is only clamped if it is also intrinsic.
2505     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2506     if (logicalWidth.type() == Intrinsic)
2507         return true;
2508
2509     // Children of a horizontal marquee do not fill the container by default.
2510     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2511     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2512     // block-flow (as well as how marquee overflow should relate to block flow).
2513     // https://bugs.webkit.org/show_bug.cgi?id=46472
2514     if (parent()->style().overflowX() == OMARQUEE) {
2515         EMarqueeDirection dir = parent()->style().marqueeDirection();
2516         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2517             return true;
2518     }
2519
2520     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2521     // In the case of columns that have a stretch alignment, we layout at the stretched size
2522     // to avoid an extra layout when applying alignment.
2523     if (parent()->isFlexibleBox()) {
2524         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2525         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2526             return true;
2527         if (!flexItemHasStretchAlignment(*this))
2528             return true;
2529     }
2530
2531     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2532     // that don't stretch their kids lay out their children at their intrinsic widths.
2533     // FIXME: Think about block-flow here.
2534     // https://bugs.webkit.org/show_bug.cgi?id=46473
2535     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2536         return true;
2537
2538     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2539     // stretching column flexbox.
2540     // FIXME: Think about block-flow here.
2541     // https://bugs.webkit.org/show_bug.cgi?id=46473
2542     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2543         return true;
2544
2545     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2546         return true;
2547
2548     return false;
2549 }
2550
2551 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2552 {
2553     const RenderStyle& containingBlockStyle = containingBlock->style();
2554     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2555     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2556
2557     if (isFloating() || isInline()) {
2558         // Inline blocks/tables and floats don't have their margins increased.
2559         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2560         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2561         return;
2562     }
2563
2564     // Case One: The object is being centered in the containing block's available logical width.
2565     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2566         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) {
2567         // Other browsers center the margin box for align=center elements so we match them here.
2568         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2569         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2570         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2571         marginStart = centeredMarginBoxStart + marginStartWidth;
2572         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2573         return;
2574     } 
2575     
2576     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2577     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2578         marginStart = valueForLength(marginStartLength, containerWidth);
2579         marginEnd = containerWidth - childWidth - marginStart;
2580         return;
2581     } 
2582     
2583     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2584     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2585         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2586     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2587         marginEnd = valueForLength(marginEndLength, containerWidth);
2588         marginStart = containerWidth - childWidth - marginEnd;
2589         return;
2590     } 
2591     
2592     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2593     // auto margins will just turn into 0.
2594     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2595     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2596 }
2597
2598 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2599 {
2600     // Make sure nobody is trying to call this with a null region.
2601     if (!region)
2602         return nullptr;
2603
2604     // If we have computed our width in this region already, it will be cached, and we can
2605     // just return it.
2606     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2607     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2608         return boxInfo;
2609
2610     // No cached value was found, so we have to compute our insets in this region.
2611     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2612     // support to cover all boxes.
2613     RenderFlowThread* flowThread = flowThreadContainingBlock();
2614     if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2615         return nullptr;
2616
2617     LogicalExtentComputedValues computedValues;
2618     computeLogicalWidthInRegion(computedValues, region);
2619
2620     // Now determine the insets based off where this object is supposed to be positioned.
2621     RenderBlock* cb = containingBlock();
2622     RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2623     RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2624     LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2625     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2626     
2627     LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2628     LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2629     LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2630     LayoutUnit logicalLeftInRegion = computedValues.m_position;
2631     LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2632     LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2633     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2634     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2635     LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2636
2637     LayoutUnit logicalLeftOffset = 0;
2638     
2639     if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2640         LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2641         if (cb->style().isLeftToRightDirection())
2642             logicalLeftDelta += startPositionDelta;
2643         else
2644             logicalRightDelta += startPositionDelta;
2645     }
2646
2647     if (cb->style().isLeftToRightDirection())
2648         logicalLeftOffset += logicalLeftDelta;
2649     else
2650         logicalLeftOffset -= (widthDelta + logicalRightDelta);
2651     
2652     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2653     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2654             || (style().isLeftToRightDirection() && logicalLeftOffset)
2655             || (!style().isLeftToRightDirection() && logicalRightOffset);
2656
2657     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2658     if (cacheFlag == CacheRenderBoxRegionInfo)
2659         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2660     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2661 }
2662
2663 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2664 {
2665     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2666     WritingMode childWritingMode = childStyle->writingMode();
2667     bool shouldFlip = false;
2668     switch (containingBlockStyle.writingMode()) {
2669     case TopToBottomWritingMode:
2670         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2671         break;
2672     case BottomToTopWritingMode:
2673         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2674         break;
2675     case RightToLeftWritingMode:
2676         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2677         break;
2678     case LeftToRightWritingMode:
2679         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2680         break;
2681     }
2682
2683     if (!containingBlockStyle.isLeftToRightDirection())
2684         shouldFlip = !shouldFlip;
2685
2686     return shouldFlip;
2687 }
2688
2689 void RenderBox::updateLogicalHeight()
2690 {
2691     LogicalExtentComputedValues computedValues;
2692     computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2693
2694     setLogicalHeight(computedValues.m_extent);
2695     setLogicalTop(computedValues.m_position);
2696     setMarginBefore(computedValues.m_margins.m_before);
2697     setMarginAfter(computedValues.m_margins.m_after);
2698 }
2699
2700 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2701 {
2702     computedValues.m_extent = logicalHeight;
2703     computedValues.m_position = logicalTop;
2704
2705     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2706     if (isTableCell() || (isInline() && !isReplaced()))
2707         return;
2708
2709     Length h;
2710     if (isOutOfFlowPositioned())
2711         computePositionedLogicalHeight(computedValues);
2712     else {
2713         RenderBlock* cb = containingBlock();
2714         bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2715     
2716         if (!hasPerpendicularContainingBlock) {
2717             bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode();
2718             computeBlockDirectionMargins(cb,
2719                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2720                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2721         }
2722
2723         // For tables, calculate margins only.
2724         if (isTable()) {
2725             if (hasPerpendicularContainingBlock) {
2726                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2727                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2728                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2729                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2730             }
2731             return;
2732         }
2733
2734         // FIXME: Account for block-flow in flexible boxes.
2735         // https://bugs.webkit.org/show_bug.cgi?id=46418
2736         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2737         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2738         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2739         bool checkMinMaxHeight = false;
2740
2741         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2742         // grab our cached flexible height.
2743         // FIXME: Account for block-flow in flexible boxes.
2744         // https://bugs.webkit.org/show_bug.cgi?id=46418
2745         if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated()
2746 #if ENABLE(CSS_GRID_LAYOUT)
2747             || parent()->isRenderGrid()
2748 #endif
2749         )) {
2750             LayoutUnit contentHeight = overrideLogicalContentHeight();
2751 #if ENABLE(CSS_GRID_LAYOUT)
2752             if (parent()->isRenderGrid() && style().logicalHeight().isAuto() && style().logicalMinHeight().isAuto() && style().overflowX() == OVISIBLE) {
2753                 LayoutUnit intrinsicContentHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2754                 if (auto minContentHeight = computeContentLogicalHeight(MinSize, Length(MinContent), intrinsicContentHeight))
2755                     contentHeight = std::max(contentHeight, constrainLogicalHeightByMinMax(minContentHeight.value(), intrinsicContentHeight));
2756             }
2757 #endif
2758             h = Length(contentHeight, Fixed);
2759         } else if (treatAsReplaced)
2760             h = Length(computeReplacedLogicalHeight(), Fixed);
2761         else {
2762             h = style().logicalHeight();
2763             checkMinMaxHeight = true;
2764         }
2765
2766         // Block children of horizontal flexible boxes fill the height of the box.
2767         // FIXME: Account for block-flow in flexible boxes.
2768         // https://bugs.webkit.org/show_bug.cgi?id=46418
2769         if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2770                 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2771             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2772             checkMinMaxHeight = false;
2773         }
2774
2775         LayoutUnit heightResult;
2776         if (checkMinMaxHeight) {
2777             LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2778             heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).valueOr(computedValues.m_extent);
2779             heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2780         } else {
2781             // The only times we don't check min/max height are when a fixed length has
2782             // been given as an override.  Just use that.  The value has already been adjusted
2783             // for box-sizing.
2784             ASSERT(h.isFixed());
2785             heightResult = h.value() + borderAndPaddingLogicalHeight();
2786         }
2787
2788         computedValues.m_extent = heightResult;
2789
2790         if (hasPerpendicularContainingBlock) {
2791             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2792             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2793                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2794                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2795         }
2796     }
2797
2798     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2799     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2800     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2801     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2802     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2803     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2804         && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2805     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2806         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2807         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2808         if (isDocumentElementRenderer())
2809             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2810         else {
2811             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2812             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2813         }
2814     }
2815 }
2816
2817 Optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2818 {
2819     if (Optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2820         return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2821     return Nullopt;
2822 }
2823
2824 Optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2825 {
2826     if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2827         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2828     return Nullopt;
2829 }
2830
2831 Optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, Optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2832 {
2833     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2834     // If that happens, this code will have to change.
2835     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent())
2836         return intrinsicContentHeight;
2837     if (logicalHeightLength.isFillAvailable())
2838         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2839     ASSERT_NOT_REACHED();
2840     return LayoutUnit(0);
2841 }
2842
2843 Optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2844 {
2845     if (height.isAuto())
2846         return heightType == MinSize ? Optional<LayoutUnit>(0) : Nullopt;
2847     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2848     // If that happens, this code will have to change.
2849     if (height.isIntrinsic())
2850         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2851     if (height.isFixed())
2852         return LayoutUnit(height.value());
2853     if (height.isPercentOrCalculated())
2854         return computePercentageLogicalHeight(height);
2855     return Nullopt;
2856 }
2857
2858 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock, bool isPerpendicularWritingMode) const
2859 {
2860     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2861     // and percent heights of children should be resolved against the multicol or paged container.
2862     if (containingBlock->isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2863         return true;
2864
2865     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2866     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2867     if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2868         return false;
2869     return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2870 }
2871
2872 Optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
2873 {
2874     Optional<LayoutUnit> availableHeight;
2875     
2876     bool skippedAutoHeightContainingBlock = false;
2877     RenderBlock* cb = containingBlock();
2878     const RenderBox* containingBlockChild = this;
2879     LayoutUnit rootMarginBorderPaddingHeight = 0;
2880     bool isHorizontal = isHorizontalWritingMode();
2881     while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb, isHorizontal != cb->isHorizontalWritingMode())) {
2882         if (cb->isBody() || cb->isDocumentElementRenderer())
2883             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2884         skippedAutoHeightContainingBlock = true;
2885         containingBlockChild = cb;
2886         cb = cb->containingBlock();
2887         cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2888     }
2889
2890     const RenderStyle& cbstyle = cb->style();
2891
2892     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2893     // explicitly specified that can be used for any percentage computations.
2894     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2895
2896     bool includeBorderPadding = isTable();
2897
2898     if (isHorizontal != cb->isHorizontalWritingMode())
2899         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2900 #if ENABLE(CSS_GRID_LAYOUT)
2901     else if (hasOverrideContainingBlockLogicalHeight())
2902         availableHeight = overrideContainingBlockContentLogicalHeight();
2903 #endif
2904     else if (is<RenderTableCell>(*cb)) {
2905         if (!skippedAutoHeightContainingBlock) {
2906             // Table cells violate what the CSS spec says to do with heights. Basically we
2907             // don't care if the cell specified a height or not. We just always make ourselves
2908             // be a percentage of the cell's current content height.
2909             if (!cb->hasOverrideLogicalContentHeight()) {
2910                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2911                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2912                 // While we can't get all cases right, we can at least detect when the cell has a specified
2913                 // height or when the table has a specified height. In these cases we want to initially have
2914                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2915                 // to grow to fill the space. This could end up being wrong in some cases, but it is
2916                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2917                 RenderTableCell& cell = downcast<RenderTableCell>(*cb);
2918                 if (scrollsOverflowY() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto()))
2919                     return LayoutUnit(0);
2920                 return Nullopt;
2921             }
2922             availableHeight = cb->overrideLogicalContentHeight();
2923             includeBorderPadding = true;
2924         }
2925     } else if (cbstyle.logicalHeight().isFixed()) {
2926         LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(cbstyle.logicalHeight().value()));
2927         availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), Nullopt));
2928     } else if (cbstyle.logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2929         // We need to recur and compute the percentage height for our containing block.
2930         if (Optional<LayoutUnit> heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight())) {
2931             LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2932             // We need to adjust for min/max height because this method does not
2933             // handle the min/max of the current block, its caller does. So the
2934             // return value from the recursive call will not have been adjusted
2935             // yet.
2936             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), Nullopt);
2937             availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2938         }
2939     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2940         // Don't allow this to affect the block' height() member variable, since this
2941         // can get called while the block is still laying out its kids.
2942         LogicalExtentComputedValues computedValues;
2943         cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2944         availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2945     } else if (cb->isRenderView())
2946         availableHeight = view().pageOrViewLogicalHeight();
2947
2948     if (!availableHeight)
2949         return availableHeight;
2950
2951     LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight);
2952     if (includeBorderPadding) {
2953         // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2954         // It is necessary to use the border-box to match WinIE's broken
2955         // box model. This is essential for sizing inside
2956         // table cells using percentage heights.
2957         result -= borderAndPaddingLogicalHeight();
2958         return std::max<LayoutUnit>(0, result);
2959     }
2960     return result;
2961 }
2962
2963 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2964 {
2965     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred);
2966 }
2967
2968 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2969 {
2970     LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercentOrCalculated()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, style().logicalMinWidth());
2971     LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercentOrCalculated()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, style().logicalMaxWidth());
2972     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2973 }
2974
2975 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const
2976 {
2977     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2978     if (widthType == MinSize && logicalWidth.isAuto())
2979         return adjustContentBoxLogicalWidthForBoxSizing(0);
2980
2981     switch (logicalWidth.type()) {
2982         case Fixed:
2983             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2984         case MinContent:
2985         case MaxContent: {
2986             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2987             LayoutUnit availableLogicalWidth = 0;
2988             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2989         }
2990         case FitContent:
2991         case FillAvailable:
2992         case Percent: 
2993         case Calculated: {
2994             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2995             // containing block's block-flow.
2996             // https://bugs.webkit.org/show_bug.cgi?id=46496
2997             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(container())) : containingBlockLogicalWidthForContent();
2998             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2999             // FIXME: Handle cases when containing block width is calculated or viewport percent.
3000             // https://bugs.webkit.org/show_bug.cgi?id=91071
3001             if (logicalWidth.isIntrinsic())
3002                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3003             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
3004                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
3005         }
3006         FALLTHROUGH;
3007         case Intrinsic:
3008         case MinIntrinsic:
3009         case Auto:
3010         case Relative:
3011         case Undefined:
3012             return intrinsicLogicalWidth();
3013     }
3014
3015     ASSERT_NOT_REACHED();
3016     return 0;
3017 }
3018
3019 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
3020 {
3021     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight()));
3022 }
3023
3024 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3025 {
3026     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight());
3027     LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight());
3028     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3029 }
3030
3031 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const
3032 {
3033     ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto());
3034     if (heightType == MinSize && logicalHeight.isAuto())
3035         return adjustContentBoxLogicalHeightForBoxSizing(Optional<LayoutUnit>(0));
3036
3037     switch (logicalHeight.type()) {
3038         case Fixed:
3039             return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3040         case Percent:
3041         case Calculated:
3042         {
3043             auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
3044             while (cb->isAnonymous() && !is<RenderView>(*cb)) {
3045                 cb = cb->containingBlock();
3046                 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3047             }
3048
3049             // FIXME: This calculation is not patched for block-flow yet.
3050             // https://bugs.webkit.org/show_bug.cgi?id=46500
3051             if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
3052                 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
3053                 RenderBlock& block = downcast<RenderBlock>(*cb);
3054                 LogicalExtentComputedValues computedValues;
3055                 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3056                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3057                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3058                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3059             }
3060             
3061             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3062             // containing block's block-flow.
3063             // https://bugs.webkit.org/show_bug.cgi?id=46496
3064             LayoutUnit availableHeight;
3065             if (isOutOfFlowPositioned())
3066                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(cb));
3067             else {
3068                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3069                 // It is necessary to use the border-box to match WinIE's broken
3070                 // box model.  This is essential for sizing inside
3071                 // table cells using percentage heights.
3072                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3073                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3074                 while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercentOrCalculated())) {
3075                     if (cb->isTableCell()) {
3076                         // Don't let table cells squeeze percent-height replaced elements
3077                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3078                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3079                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3080                     }
3081                     downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3082                     cb = cb->containingBlock();
3083                 }
3084             }
3085             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3086         }
3087         case MinContent:
3088         case MaxContent:
3089         case FitContent:
3090         case FillAvailable:
3091             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3092         default:
3093             return intrinsicLogicalHeight();
3094     }
3095 }
3096
3097 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3098 {
3099     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), Nullopt);
3100 }
3101
3102 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3103 {
3104     // We need to stop here, since we don't want to increase the height of the table
3105     // artificially.  We're going to rely on this cell getting expanded to some new
3106     // height, and then when we lay out again we'll use the calculation below.
3107     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3108         if (hasOverrideLogicalContentHeight())
3109             return overrideLogicalContentHeight();
3110         return logicalHeight() - borderAndPaddingLogicalHeight();
3111     }
3112
3113     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3114         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3115         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
3116         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3117     }
3118
3119     if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, Nullopt))
3120         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3121
3122     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3123     // https://bugs.webkit.org/show_bug.cgi?id=46500
3124     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3125         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3126         LogicalExtentComputedValues computedValues;
3127         block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3128         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3129         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3130     }
3131
3132     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3133     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3134     if (heightType == ExcludeMarginBorderPadding) {
3135         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3136         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3137     }
3138     return availableHeight;
3139 }
3140
3141 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3142 {
3143     if (isTableCell()) {
3144         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3145         // we may just do it with an extra anonymous block inside the cell.
3146         marginBefore = 0;
3147         marginAfter = 0;
3148         return;
3149     }
3150
3151     // Margins are calculated with respect to the logical width of
3152     // the containing block (8.3)
3153     LayoutUnit cw = containingBlockLogicalWidthForContent();
3154     const RenderStyle& containingBlockStyle = containingBlock->style();
3155     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3156     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3157 }
3158
3159 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
3160 {
3161     LayoutUnit marginBefore;
3162     LayoutUnit marginAfter;
3163     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3164     containingBlock->setMarginBeforeForChild(*this, marginBefore);
3165     containingBlock->setMarginAfterForChild(*this, marginAfter);
3166 }
3167
3168 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3169 {
3170     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3171         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3172
3173     if (is<RenderBox>(*containingBlock)) {
3174         bool isFixedPosition = style().position() == FixedPosition;
3175
3176         RenderFlowThread* flowThread = flowThreadContainingBlock();
3177         if (!flowThread) {
3178             if (isFixedPosition && is<RenderView>(*containingBlock))
3179                 return downcast<RenderView>(*containingBlock).clientLogicalWidthForFixedPosition();
3180
3181             return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3182         }
3183
3184         if (isFixedPosition && is<RenderNamedFlowThread>(*containingBlock))
3185             return containingBlock->view().clientLogicalWidth();
3186
3187         if (!is<RenderBlock>(*containingBlock))
3188             return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3189
3190         const RenderBlock& cb = downcast<RenderBlock>(*containingBlock);
3191         RenderBoxRegionInfo* boxInfo = nullptr;
3192         if (!region) {
3193             if (is<RenderFlowThread>(*containingBlock) && !checkForPerpendicularWritingMode)
3194                 return downcast<RenderFlowThread>(*containingBlock).contentLogicalWidthOfFirstRegion();
3195             if (isWritingModeRoot()) {
3196                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3197                 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3198                 if (cbRegion)
3199                     boxInfo = cb.renderBoxRegionInfo(cbRegion);
3200             }
3201         } else if (flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3202             RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3203             boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3204         }
3205         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3206     }
3207
3208     ASSERT(containingBlock->isInFlowPositioned());
3209
3210     const auto& flow = downcast<RenderInline>(*containingBlock);
3211     InlineFlowBox* first = flow.firstLineBox();
3212     InlineFlowBox* last = flow.lastLineBox();
3213
3214     // If the containing block is empty, return a width of 0.
3215     if (!first || !last)
3216         return 0;
3217
3218     LayoutUnit fromLeft;
3219     LayoutUnit fromRight;
3220     if (containingBlock->style().isLeftToRightDirection()) {
3221         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3222         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3223     } else {
3224         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3225         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3226     }
3227
3228     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3229 }
3230
3231 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3232 {
3233     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3234         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3235
3236     if (containingBlock->isBox()) {
3237         bool isFixedPosition = style().position() == FixedPosition;
3238
3239         if (isFixedPosition && is<RenderView>(*containingBlock))
3240             return downcast<RenderView>(*containingBlock).clientLogicalHeightForFixedPosition();
3241
3242         const RenderBlock* cb = is<RenderBlock>(*containingBlock) ? downcast<RenderBlock>(containingBlock) : containingBlock->containingBlock();
3243         LayoutUnit result = cb->clientLogicalHeight();
3244         RenderFlowThread* flowThread = flowThreadContainingBlock();
3245         if (flowThread && is<RenderFlowThread>(*containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3246             if (is<RenderNamedFlowThread>(*containingBlock) && isFixedPosition)
3247                 return containingBlock->view().clientLogicalHeight();
3248             return downcast<RenderFlowThread>(*containingBlock).contentLogicalHeightOfFirstRegion();
3249         }
3250         return result;
3251     }
3252         
3253     ASSERT(containingBlock->isInFlowPositioned());
3254
3255     const auto& flow = downcast<RenderInline>(*containingBlock);
3256     InlineFlowBox* first = flow.firstLineBox();
3257     InlineFlowBox* last = flow.lastLineBox();
3258
3259     // If the containing block is empty, return a height of 0.
3260     if (!first || !last)
3261         return 0;
3262
3263     LayoutUnit heightResult;
3264     LayoutRect boundingBox = flow.linesBoundingBox();
3265     if (containingBlock->isHorizontalWritingMode())
3266         heightResult = boundingBox.height();
3267     else
3268         heightResult = boundingBox.width();
3269     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3270     return heightResult;
3271 }
3272
3273 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3274 {
3275     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3276         return;
3277
3278     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3279     if (child->parent()->style().direction() == LTR) {
3280         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3281         for (auto* current = child->parent(); current && current != containerBlock; current = current->container()) {
3282             if (is<RenderBox>(*current)) {
3283                 staticPosition += downcast<RenderBox>(*current).logicalLeft();
3284                 if (region && is<RenderBlock>(*current)) {
3285                     const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3286                     region = currentBlock.clampToStartAndEndRegions(region);
3287                     RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3288                     if (boxInfo)
3289                         staticPosition += boxInfo->logicalLeft();
3290                 }
3291             }
3292         }
3293         logicalLeft.setValue(Fixed, staticPosition);
3294     } else {
3295         RenderBox& enclosingBox = child->parent()->enclosingBox();
3296         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3297         for (RenderElement* current = &enclosingBox; current; current = current->container()) {
3298             if (is<RenderBox>(*current)) {
3299                 if (current != containerBlock)
3300                     staticPosition -= downcast<RenderBox>(*current).logicalLeft();
3301                 if (current == &enclosingBox)
3302                     staticPosition -= enclosingBox.logicalWidth();
3303                 if (region && is<RenderBlock>(*current)) {
3304                     const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3305                     region = currentBlock.clampToStartAndEndRegions(region);
3306                     RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3307                     if (boxInfo) {
3308                         if (current != containerBlock)
3309                             staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3310                         if (current == &enclosingBox)
3311                             staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3312                     }
3313                 }
3314             }
3315             if (current == containerBlock)
3316                 break;
3317         }
3318         logicalRight.setValue(Fixed, staticPosition);
3319     }
3320 }
3321
3322 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3323 {
3324     if (isReplaced()) {
3325         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3326         // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3327         computePositionedLogicalWidthReplaced(computedValues);
3328         return;
3329     }
3330
3331     // QUESTIONS
3332     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3333     // the type 'static' in determining whether to calculate the static distance?
3334     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3335
3336     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3337     // than or less than the computed width().  Be careful of box-sizing and
3338     // percentage issues.
3339
3340     // The following is based off of the W3C Working Draft from April 11, 2006 of
3341     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3342     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3343     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3344     // correspond to text from the spec)
3345
3346
3347     // We don't use containingBlock(), since we may be positioned by an enclosing
3348     // relative positioned inline.
3349     const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3350     
3351     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3352
3353     // Use the container block's direction except when calculating the static distance
3354     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3355     // of the CSS 2.1 test suite
3356     TextDirection containerDirection = containerBlock->style().direction();
3357
3358     bool isHorizontal = isHorizontalWritingMode();
3359     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3360     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3361     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3362
3363     Length logicalLeftLength = style().logicalLeft();
3364     Length logicalRightLength = style().logicalRight();
3365
3366     /*---------------------------------------------------------------------------*\
3367      * For the purposes of this section and the next, the term "static position"
3368      * (of an element) refers, roughly, to the position an element would have had
3369      * in the normal flow. More precisely:
3370      *
3371      * * The static position for 'left' is the distance from the left edge of the
3372      *   containing block to the left margin edge of a hypothetical box that would
3373      *   have been the first box of the element if its 'position' property had
3374      *   been 'static' and 'float' had been 'none'. The value is negative if the
3375      *   hypothetical box is to the left of the containing block.
3376      * * The static position for 'right' is the distance from the right edge of the
3377      *   containing block to the right margin edge of the same hypothetical box as
3378      *   above. The value is positive if the hypothetical box is to the left of the
3379      *   containing block's edge.
3380      *
3381      * But rather than actually calculating the dimensions of that hypothetical box,
3382      * user agents are free to make a guess at its probable position.
3383      *
3384      * For the purposes of calculating the static position, the containing block of
3385      * fixed positioned elements is the initial containing block instead of the
3386      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3387      * origin.
3388     \*---------------------------------------------------------------------------*/
3389
3390     // see FIXME 1
3391     // Calculate the static distance if needed.
3392     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3393     
3394     // Calculate constraint equation values for 'width' case.
3395     computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection,
3396                                        containerLogicalWidth, bordersPlusPadding,
3397                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3398                                        computedValues);
3399
3400     // Calculate constraint equation values for 'max-width' case.
3401     if (!style().logicalMaxWidth().isUndefined()) {
3402         LogicalExtentComputedValues maxValues;
3403
3404         computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection,
3405                                            containerLogicalWidth, bordersPlusPadding,
3406                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3407                                            maxValues);
3408
3409         if (computedValues.m_extent > maxValues.m_extent) {
3410             computedValues.m_extent = maxValues.m_extent;
3411             computedValues.m_position = maxValues.m_position;
3412             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3413             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3414         }
3415     }
3416
3417     // Calculate constraint equation values for 'min-width' case.
3418     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3419         LogicalExtentComputedValues minValues;
3420
3421         computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection,
3422                                            containerLogicalWidth, bordersPlusPadding,
3423                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3424                                            minValues);
3425
3426         if (computedValues.m_extent < minValues.m_extent) {
3427             computedValues.m_extent = minValues.m_extent;
3428             computedValues.m_position = minValues.m_position;
3429             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3430             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3431         }
3432     }
3433
3434     computedValues.m_extent += bordersPlusPadding;
3435     
3436     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3437     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3438     RenderFlowThread* flowThread = flowThreadContainingBlock();
3439     if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3440         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3441         LayoutUnit logicalLeftPos = computedValues.m_position;
3442         const RenderBlock& renderBlock = downcast<RenderBlock>(*containerBlock);
3443         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3444         RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3445         if (cbRegion) {
3446             RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3447             if (boxInfo) {
3448                 logicalLeftPos += boxInfo->logicalLeft();
3449                 computedValues.m_position = logicalLeftPos;
3450             }
3451         }
3452     }
3453 }
3454
3455 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
3456 {
3457     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3458     // 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.
3459     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style().isFlippedBlocksWritingMode()) {
3460         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3461         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
3462     } else
3463         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
3464 }
3465
3466 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
3467                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3468                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3469                                                    LogicalExtentComputedValues& computedValues) const
3470 {
3471     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3472     if (widthType == MinSize && logicalWidth.isAuto())
3473         logicalWidth = Length(0, Fixed);
3474     else if (logicalWidth.isIntrinsic())
3475         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3476
3477     // 'left' and 'right' cannot both be 'auto' because one would of been
3478     // converted to the static position already
3479     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3480
3481     LayoutUnit logicalLeftValue = 0;
3482
3483     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3484
3485     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3486     bool logicalLeftIsAuto = logicalLeft.isAuto();
3487     bool logicalRightIsAuto = logicalRight.isAuto();
3488     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3489     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3490
3491     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3492         /*-----------------------------------------------------------------------*\
3493          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3494          * right' are 'auto', solve the equation under the extra constraint that
3495          * the two margins get equal values, unless this would make them negative,
3496          * in which case when direction of the containing block is 'ltr' ('rtl'),
3497          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3498          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3499          * solve the equation for that value. If the values are over-constrained,
3500          * ignore the value for 'left' (in case the 'direction' property of the
3501          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3502          * and solve for that value.
3503         \*-----------------------------------------------------------------------*/
3504         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3505         // case because the value is not used for any further calculations.
3506
3507         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3508         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3509
3510         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3511
3512         // Margins are now the only unknown
3513         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3514             // Both margins auto, solve for equality
3515             if (availableSpace >= 0) {
3516                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3517                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3518             } else {
3519                 // Use the containing block's direction rather than the parent block's
3520                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3521                 if (containerDirection == LTR) {
3522                     marginLogicalLeftValue = 0;
3523                     marginLogicalRightValue = availableSpace; // will be negative
3524                 } else {
3525                     marginLogicalLeftValue = availableSpace; // will be negative
3526                     marginLogicalRightValue = 0;
3527                 }
3528             }
3529         } else if (marginLogicalLeft.isAuto()) {
3530             // Solve for left margin
3531             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3532             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3533         } else if (marginLogicalRight.isAuto()) {
3534             // Solve for right margin
3535             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3536             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3537         } else {
3538             // Over-constrained, solve for left if direction is RTL
3539             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3540             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3541
3542             // Use the containing block's direction rather than the parent block's
3543             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3544             if (containerDirection == RTL)
3545                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3546         }
3547     } else {
3548         /*--------------------------------------------------------------------*\
3549          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3550          * to 0, and pick the one of the following six rules that applies.
3551          *
3552          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3553          *    width is shrink-to-fit. Then solve for 'left'
3554          *
3555          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3556          * ------------------------------------------------------------------
3557          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3558          *    the 'direction' property of the containing block is 'ltr' set
3559          *    'left' to the static position, otherwise set 'right' to the
3560          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3561          *    or 'right' (if 'direction' is 'ltr').
3562          * ------------------------------------------------------------------
3563          *
3564          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3565          *    width is shrink-to-fit . Then solve for 'right'
3566          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3567          *    for 'left'
3568          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3569          *    for 'width'
3570          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3571          *    for 'right'
3572          *
3573          * Calculation of the shrink-to-fit width is similar to calculating the
3574          * width of a table cell using the automatic table layout algorithm.
3575          * Roughly: calculate the preferred width by formatting the content
3576          * without breaking lines other than where explicit line breaks occur,
3577          * and also calculate the preferred minimum width, e.g., by trying all
3578          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3579          * Thirdly, calculate the available width: this is found by solving
3580          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3581          * to 0.
3582          *
3583          * Then the shrink-to-fit width is:
3584          * min(max(preferred minimum width, available width), preferred width).
3585         \*--------------------------------------------------------------------*/
3586         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3587         // because the value is not used for any further calculations.
3588
3589         // Calculate margins, 'auto' margins are ignored.
3590         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3591         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3592
3593         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3594
3595         // FIXME: Is there a faster way to find the correct case?
3596         // Use rule/case that applies.
3597         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3598             // RULE 1: (use shrink-to-fit for width, and solve of left)
3599             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3600
3601             // FIXME: would it be better to have shrink-to-fit in one step?
3602             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3603             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3604             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3605             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3606             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3607         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3608             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3609             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3610
3611             // FIXME: would it be better to have shrink-to-fit in one step?
3612             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3613             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3614             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3615             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3616         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3617             // RULE 4: (solve for left)
3618             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3619             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3620         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3621             // RULE 5: (solve for width)
3622             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3623             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3624         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3625             // RULE 6: (no need solve for right)
3626             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3627             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3628         }
3629     }
3630
3631     // Use computed values to calculate the horizontal position.
3632
3633     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3634     // positioned, inline because right now, it is using the logical left position
3635     // of the first line box when really it should use the last line box.  When
3636     // this is fixed elsewhere, this block should be removed.
3637     if (is<RenderInline>(*containerBlock) && !containerBlock->style().isLeftToRightDirection()) {
3638         const auto& flow = downcast<RenderInline>(*containerBlock);
3639         InlineFlowBox* firstLine = flow.firstLineBox();
3640         InlineFlowBox* lastLine = flow.lastLineBox();
3641         if (firstLine && lastLine && firstLine != lastLine) {
3642             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3643             return;
3644         }
3645     }
3646
3647     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3648     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3649 }
3650
3651 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3652 {
3653     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3654         return;
3655     
3656     // FIXME: The static distance computation has not been patched for mixed writing modes.
3657     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3658     for (RenderElement* container = child->parent(); container && container != containerBlock; container = container->container()) {
3659         if (is<RenderBox>(*container) && !is<RenderTableRow>(*container))
3660             staticLogicalTop += downcast<RenderBox>(*container).logicalTop();
3661     }
3662     logicalTop.setValue(Fixed, staticLogicalTop);
3663 }
3664
3665 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3666 {
3667     if (isReplaced()) {
3668         computePositionedLogicalHeightReplaced(computedValues);
3669         return;
3670     }
3671
3672     // The following is based off of the W3C Working Draft from April 11, 2006 of
3673     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3674     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3675     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3676     // correspond to text from the spec)
3677
3678
3679     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3680     const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3681
3682     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3683
3684     const RenderStyle& styleToUse = style();
3685     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3686     const Length marginBefore = styleToUse.marginBefore();
3687     const Length marginAfter = styleToUse.marginAfter();
3688     Length logicalTopLength = styleToUse.logicalTop();
3689     Length logicalBottomLength = styleToUse.logicalBottom();
3690
3691     /*---------------------------------------------------------------------------*\
3692      * For the purposes of this section and the next, the term "static position"
3693      * (of an element) refers, roughly, to the position an element would have had
3694      * in the normal flow. More precisely, the static position for 'top' is the
3695      * distance from the top edge of the containing block to the top margin edge
3696      * of a hypothetical box that would have been the first box of the element if
3697      * its 'position' property had been 'static' and 'float' had been 'none'. The
3698      * value is negative if the hypothetical box is above the containing block.
3699      *
3700      * But rather than actually calculating the dimensions of that hypothetical
3701      * box, user agents are free to make a guess at its probable position.
3702      *
3703      * For the purposes of calculating the static position, the containing block
3704      * of fixed positioned elements is the initial containing block instead of
3705      * the viewport.
3706     \*---------------------------------------------------------------------------*/
3707
3708     // see FIXME 1
3709     // Calculate the static distance if needed.
3710     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3711
3712     // Calculate constraint equation values for 'height' case.
3713     LayoutUnit logicalHeight = computedValues.m_extent;
3714     computePositionedLogicalHeightUsing(MainOrPreferredSize, styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3715                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3716                                         computedValues);
3717
3718     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3719     // see FIXME 2
3720
3721     // Calculate constraint equation values for 'max-height' case.
3722     if (!styleToUse.logicalMaxHeight().isUndefined()) {
3723         LogicalExtentComputedValues maxValues;
3724
3725         computePositionedLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3726                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3727                                             maxValues);
3728
3729         if (computedValues.m_extent > maxValues.m_extent) {
3730             computedValues.m_extent = maxValues.m_extent;
3731             computedValues.m_position = maxValues.m_position;
3732             computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3733             computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3734         }
3735     }
3736
3737     // Calculate constraint equation values for 'min-height' case.
3738     if (!styleToUse.logicalMinHeight().isZero() || styleToUse.logicalMinHeight().isIntrinsic()) {
3739         LogicalExtentComputedValues minValues;
3740
3741         computePositionedLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3742                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3743                                             minValues);
3744
3745         if (computedValues.m_extent < minValues.m_extent) {
3746             computedValues.m_extent = minValues.m_extent;
3747             computedValues.m_position = minValues.m_position;
3748             computedValues.m_margins.m_before = minValues.m_margins.m_before;
3749             computedValues.m_margins.m_after = minValues.m_margins.m_after;
3750         }
3751     }
3752
3753     // Set final height value.
3754     computedValues.m_extent += bordersPlusPadding;
3755     
3756     // Adjust logicalTop if we need to for perpendicular writing modes in regions.
3757     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3758     RenderFlowThread* flowThread = flowThreadContainingBlock();
3759     if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3760         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3761         LayoutUnit logicalTopPos = computedValues.m_position;
3762         const RenderBlock& renderBox = downcast<RenderBlock>(*containerBlock);
3763         LayoutUnit cbPageOffset = renderBox.offsetFromLogicalTopOfFirstPage() - logicalLeft();
3764         RenderRegion* cbRegion = renderBox.regionAtBlockOffset(cbPageOffset);
3765         if (cbRegion) {
3766             RenderBoxRegionInfo* boxInfo = renderBox.renderBoxRegionInfo(cbRegion);
3767             if (boxInfo) {
3768                 logicalTopPos += boxInfo->logicalLeft();
3769                 computedValues.m_position = logicalTopPos;
3770             }
3771         }
3772     }
3773 }
3774
3775 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3776 {
3777     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3778     // 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.
3779     if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3780         || (child->style().isFlippedBlocksWritingMode() != containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3781         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3782
3783     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3784     if (containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3785         if (child->isHorizontalWritingMode())
3786             logicalTopPos += containerBlock->borderBottom();
3787         else
3788             logicalTopPos += containerBlock->borderRight();
3789     } else {
3790         if (child->isHorizontalWritingMode())
3791             logicalTopPos += containerBlock->borderTop();
3792         else
3793             logicalTopPos += containerBlock->borderLeft();
3794     }
3795 }
3796
3797 void RenderBox::computePositionedLogicalHeightUsing(SizeType heightType, Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3798                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3799                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
3800                             &