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