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