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