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