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