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