Fix non-iOS builds.
[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 static inline bool shouldAppyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2114 {
2115 #if PLATFORM(IOS)
2116     if (!repaintContainer || repaintContainer != containerBox)
2117         return true;
2118
2119     return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2120 #else
2121     UNUSED_PARAM(repaintContainer);
2122     UNUSED_PARAM(containerBox);
2123     return true;
2124 #endif
2125 }
2126
2127 void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
2128 {
2129     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2130     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2131     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2132     // properly even during layout, since the rect remains flipped all the way until the end.
2133     //
2134     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2135     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2136     // physical coordinate space of the repaintContainer.
2137     const RenderStyle& styleToUse = style();
2138     // LayoutState is only valid for root-relative, non-fixed position repainting
2139     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2140         LayoutState* layoutState = view().layoutState();
2141
2142         if (layer() && layer()->transform())
2143             rect = LayoutRect(layer()->transform()->mapRect(pixelSnappedForPainting(rect, document().deviceScaleFactor())));
2144
2145         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2146         if (styleToUse.hasInFlowPosition() && layer())
2147             rect.move(layer()->offsetForInFlowPosition());
2148
2149         rect.moveBy(location());
2150         rect.move(layoutState->m_paintOffset);
2151         if (layoutState->m_clipped)
2152             rect.intersect(layoutState->m_clipRect);
2153         return;
2154     }
2155
2156     if (hasReflection())
2157         rect.unite(reflectedRect(rect));
2158
2159     if (repaintContainer == this) {
2160         if (repaintContainer->style().isFlippedBlocksWritingMode())
2161             flipForWritingMode(rect);
2162         return;
2163     }
2164
2165     bool containerSkipped;
2166     auto o = container(repaintContainer, &containerSkipped);
2167     if (!o)
2168         return;
2169     
2170     EPosition position = styleToUse.position();
2171
2172     // This code isn't necessary for in-flow RenderFlowThreads.
2173     // Don't add the location of the region in the flow thread for absolute positioned
2174     // elements because their absolute position already pushes them down through
2175     // the regions so adding this here and then adding the topLeft again would cause
2176     // us to add the height twice.
2177     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2178     // will already contain the portion rect of the region.
2179     if (o->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2180         RenderRegion* firstRegion = nullptr;
2181         RenderRegion* lastRegion = nullptr;
2182         if (toRenderFlowThread(o)->getRegionRangeForBox(this, firstRegion, lastRegion))
2183             rect.moveBy(firstRegion->flowThreadPortionRect().location());
2184     }
2185
2186     if (isWritingModeRoot() && !isOutOfFlowPositioned())
2187         flipForWritingMode(rect);
2188
2189     LayoutPoint topLeft = rect.location();
2190     topLeft.move(locationOffset());
2191
2192     // We are now in our parent container's coordinate space.  Apply our transform to obtain a bounding box
2193     // in the parent's coordinate space that encloses us.
2194     if (hasLayer() && layer()->transform()) {
2195         fixed = position == FixedPosition;
2196         rect = LayoutRect(layer()->transform()->mapRect(pixelSnappedForPainting(rect, document().deviceScaleFactor())));
2197         topLeft = rect.location();
2198         topLeft.move(locationOffset());
2199     } else if (position == FixedPosition)
2200         fixed = true;
2201
2202     if (position == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline())
2203         topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(this);
2204     else if (styleToUse.hasInFlowPosition() && layer()) {
2205         // Apply the relative position offset when invalidating a rectangle.  The layer
2206         // is translated, but the render box isn't, so we need to do this to get the
2207         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2208         // flag on the RenderObject has been cleared, so use the one on the style().
2209         topLeft += layer()->offsetForInFlowPosition();
2210     }
2211
2212     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2213     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2214     rect.setLocation(topLeft);
2215     if (o->hasOverflowClip()) {
2216         RenderBox* containerBox = toRenderBox(o);
2217         if (shouldAppyContainersClipAndOffset(repaintContainer, containerBox)) {
2218             containerBox->applyCachedClipAndScrollOffsetForRepaint(rect);
2219             if (rect.isEmpty())
2220                 return;
2221         }
2222     }
2223
2224     if (containerSkipped) {
2225         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2226         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
2227         rect.move(-containerOffset);
2228         return;
2229     }
2230
2231     o->computeRectForRepaint(repaintContainer, rect, fixed);
2232 }
2233
2234 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2235 {
2236     if (oldRect.location() != m_frameRect.location()) {
2237         LayoutRect newRect = m_frameRect;
2238         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2239         // since the object may not have gotten a layout.
2240         m_frameRect = oldRect;
2241         repaint();
2242         repaintOverhangingFloats(true);
2243         m_frameRect = newRect;
2244         repaint();
2245         repaintOverhangingFloats(true);
2246     }
2247 }
2248
2249 void RenderBox::repaintOverhangingFloats(bool)
2250 {
2251 }
2252
2253 void RenderBox::updateLogicalWidth()
2254 {
2255     LogicalExtentComputedValues computedValues;
2256     computeLogicalWidthInRegion(computedValues);
2257
2258     setLogicalWidth(computedValues.m_extent);
2259     setLogicalLeft(computedValues.m_position);
2260     setMarginStart(computedValues.m_margins.m_start);
2261     setMarginEnd(computedValues.m_margins.m_end);
2262 }
2263
2264 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2265 {
2266     computedValues.m_extent = logicalWidth();
2267     computedValues.m_position = logicalLeft();
2268     computedValues.m_margins.m_start = marginStart();
2269     computedValues.m_margins.m_end = marginEnd();
2270
2271     if (isOutOfFlowPositioned()) {
2272         // FIXME: This calculation is not patched for block-flow yet.
2273         // https://bugs.webkit.org/show_bug.cgi?id=46500
2274         computePositionedLogicalWidth(computedValues, region);
2275         return;
2276     }
2277
2278     // If layout is limited to a subtree, the subtree root's logical width does not change.
2279     if (element() && view().frameView().layoutRoot(true) == this)
2280         return;
2281
2282     // The parent box is flexing us, so it has increased or decreased our
2283     // width.  Use the width from the style context.
2284     // FIXME: Account for block-flow in flexible boxes.
2285     // https://bugs.webkit.org/show_bug.cgi?id=46418
2286     if (hasOverrideWidth() && (style().borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
2287         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2288         return;
2289     }
2290
2291     // FIXME: Account for block-flow in flexible boxes.
2292     // https://bugs.webkit.org/show_bug.cgi?id=46418
2293     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2294     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2295     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2296
2297     const RenderStyle& styleToUse = style();
2298     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2299
2300     RenderBlock* cb = containingBlock();
2301     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2302     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2303     
2304     if (isInline() && !isInlineBlockOrInlineTable()) {
2305         // just calculate margins
2306         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2307         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2308         if (treatAsReplaced)
2309             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2310         return;
2311     }
2312
2313     // Width calculations
2314     if (treatAsReplaced)
2315         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2316     else {
2317         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2318         if (hasPerpendicularContainingBlock)
2319             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2320         LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2321         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2322     }
2323
2324     // Margin calculations.
2325     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2326         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2327         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2328     } else {
2329         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2330         if (avoidsFloats() && cb->containsFloats())
2331             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2332         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2333         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2334             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2335             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2336     }
2337     
2338     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2339         && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated()
2340 #if ENABLE(CSS_GRID_LAYOUT)
2341         && !cb->isRenderGrid()
2342 #endif
2343         ) {
2344         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
2345         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2346         if (hasInvertedDirection)
2347             computedValues.m_margins.m_start = newMargin;
2348         else
2349             computedValues.m_margins.m_end = newMargin;
2350     }
2351 }
2352
2353 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2354 {
2355     LayoutUnit marginStart = 0;
2356     LayoutUnit marginEnd = 0;
2357     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2358 }
2359
2360 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2361 {
2362     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2363     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2364     return availableLogicalWidth - marginStart - marginEnd;
2365 }
2366
2367 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2368 {
2369     if (logicalWidthLength.type() == FillAvailable)
2370         return fillAvailableMeasure(availableLogicalWidth);
2371
2372     LayoutUnit minLogicalWidth = 0;
2373     LayoutUnit maxLogicalWidth = 0;
2374     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2375
2376     if (logicalWidthLength.type() == MinContent)
2377         return minLogicalWidth + borderAndPadding;
2378
2379     if (logicalWidthLength.type() == MaxContent)
2380         return maxLogicalWidth + borderAndPadding;
2381
2382     if (logicalWidthLength.type() == FitContent) {
2383         minLogicalWidth += borderAndPadding;
2384         maxLogicalWidth += borderAndPadding;
2385         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2386     }
2387
2388     ASSERT_NOT_REACHED();
2389     return 0;
2390 }
2391
2392 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2393     const RenderBlock* cb, RenderRegion* region) const
2394 {
2395     if (!logicalWidth.isIntrinsicOrAuto()) {
2396         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2397         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2398     }
2399
2400     if (logicalWidth.isIntrinsic())
2401         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2402
2403     LayoutUnit marginStart = 0;
2404     LayoutUnit marginEnd = 0;
2405     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2406
2407     if (shrinkToAvoidFloats() && cb->containsFloats())
2408         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2409
2410     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2411         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2412     return logicalWidthResult;
2413 }
2414
2415 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2416 {
2417     auto parent = flexitem.parent();
2418     return flexitem.style().alignSelf() == AlignStretch || (flexitem.style().alignSelf() == AlignAuto && parent->style().alignItems() == AlignStretch);
2419 }
2420
2421 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2422 {
2423     auto parent = flexitem.parent();
2424     if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2425         return true;
2426
2427     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2428     if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2429         return true;
2430     return false;
2431 }
2432
2433 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2434 {
2435     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2436     // but they allow text to sit on the same line as the marquee.
2437     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2438         return true;
2439
2440     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2441     // min-width and width.  max-width is only clamped if it is also intrinsic.
2442     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2443     if (logicalWidth.type() == Intrinsic)
2444         return true;
2445
2446     // Children of a horizontal marquee do not fill the container by default.
2447     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2448     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2449     // block-flow (as well as how marquee overflow should relate to block flow).
2450     // https://bugs.webkit.org/show_bug.cgi?id=46472
2451     if (parent()->style().overflowX() == OMARQUEE) {
2452         EMarqueeDirection dir = parent()->style().marqueeDirection();
2453         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2454             return true;
2455     }
2456
2457     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2458     // In the case of columns that have a stretch alignment, we go ahead and layout at the
2459     // stretched size to avoid an extra layout when applying alignment.
2460     if (parent()->isFlexibleBox()) {
2461         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2462         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2463             return true;
2464         if (!flexItemHasStretchAlignment(*this))
2465             return true;
2466     }
2467
2468     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2469     // that don't stretch their kids lay out their children at their intrinsic widths.
2470     // FIXME: Think about block-flow here.
2471     // https://bugs.webkit.org/show_bug.cgi?id=46473
2472     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2473         return true;
2474
2475     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2476     // stretching column flexbox.
2477     // FIXME: Think about block-flow here.
2478     // https://bugs.webkit.org/show_bug.cgi?id=46473
2479     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (isHTMLInputElement(element()) || element()->hasTagName(selectTag) || element()->hasTagName(buttonTag) || isHTMLTextAreaElement(element()) || element()->hasTagName(legendTag)))
2480         return true;
2481
2482     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2483         return true;
2484
2485     return false;
2486 }
2487
2488 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2489 {
2490     const RenderStyle& containingBlockStyle = containingBlock->style();
2491     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2492     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2493
2494     if (isFloating() || isInline()) {
2495         // Inline blocks/tables and floats don't have their margins increased.
2496         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2497         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2498         return;
2499     }
2500
2501     // Case One: The object is being centered in the containing block's available logical width.
2502     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2503         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) {
2504         // Other browsers center the margin box for align=center elements so we match them here.
2505         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2506         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2507         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2508         marginStart = centeredMarginBoxStart + marginStartWidth;
2509         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2510         return;
2511     } 
2512     
2513     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2514     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2515         marginStart = valueForLength(marginStartLength, containerWidth);
2516         marginEnd = containerWidth - childWidth - marginStart;
2517         return;
2518     } 
2519     
2520     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2521     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2522         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2523     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2524         marginEnd = valueForLength(marginEndLength, containerWidth);
2525         marginStart = containerWidth - childWidth - marginEnd;
2526         return;
2527     } 
2528     
2529     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2530     // auto margins will just turn into 0.
2531     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2532     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2533 }
2534
2535 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2536 {
2537     // Make sure nobody is trying to call this with a null region.
2538     if (!region)
2539         return 0;
2540
2541     // If we have computed our width in this region already, it will be cached, and we can
2542     // just return it.
2543     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2544     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2545         return boxInfo;
2546
2547     // No cached value was found, so we have to compute our insets in this region.
2548     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2549     // support to cover all boxes.
2550     RenderFlowThread* flowThread = flowThreadContainingBlock();
2551     if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2552         return 0;
2553
2554     LogicalExtentComputedValues computedValues;
2555     computeLogicalWidthInRegion(computedValues, region);
2556
2557     // Now determine the insets based off where this object is supposed to be positioned.
2558     RenderBlock* cb = containingBlock();
2559     RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2560     RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2561     LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2562     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2563     
2564     LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2565     LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2566     LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2567     LayoutUnit logicalLeftInRegion = computedValues.m_position;
2568     LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2569     LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2570     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2571     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2572     LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2573
2574     LayoutUnit logicalLeftOffset = 0;
2575     
2576     if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2577         LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2578         if (cb->style().isLeftToRightDirection())
2579             logicalLeftDelta += startPositionDelta;
2580         else
2581             logicalRightDelta += startPositionDelta;
2582     }
2583
2584     if (cb->style().isLeftToRightDirection())
2585         logicalLeftOffset += logicalLeftDelta;
2586     else
2587         logicalLeftOffset -= (widthDelta + logicalRightDelta);
2588     
2589     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2590     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2591             || (style().isLeftToRightDirection() && logicalLeftOffset)
2592             || (!style().isLeftToRightDirection() && logicalRightOffset);
2593
2594     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2595     if (cacheFlag == CacheRenderBoxRegionInfo)
2596         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2597     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2598 }
2599
2600 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2601 {
2602     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2603     WritingMode childWritingMode = childStyle->writingMode();
2604     bool shouldFlip = false;
2605     switch (containingBlockStyle.writingMode()) {
2606     case TopToBottomWritingMode:
2607         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2608         break;
2609     case BottomToTopWritingMode:
2610         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2611         break;
2612     case RightToLeftWritingMode:
2613         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2614         break;
2615     case LeftToRightWritingMode:
2616         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2617         break;
2618     }
2619
2620     if (!containingBlockStyle.isLeftToRightDirection())
2621         shouldFlip = !shouldFlip;
2622
2623     return shouldFlip;
2624 }
2625
2626 void RenderBox::updateLogicalHeight()
2627 {
2628     LogicalExtentComputedValues computedValues;
2629     computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2630
2631     setLogicalHeight(computedValues.m_extent);
2632     setLogicalTop(computedValues.m_position);
2633     setMarginBefore(computedValues.m_margins.m_before);
2634     setMarginAfter(computedValues.m_margins.m_after);
2635 }
2636
2637 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2638 {
2639     computedValues.m_extent = logicalHeight;
2640     computedValues.m_position = logicalTop;
2641
2642     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2643     if (isTableCell() || (isInline() && !isReplaced()))
2644         return;
2645
2646     Length h;
2647     if (isOutOfFlowPositioned())
2648         computePositionedLogicalHeight(computedValues);
2649     else {
2650         RenderBlock* cb = containingBlock();
2651         bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2652     
2653         if (!hasPerpendicularContainingBlock) {
2654             bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode();
2655             computeBlockDirectionMargins(cb,
2656                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2657                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2658         }
2659
2660         // For tables, calculate margins only.
2661         if (isTable()) {
2662             if (hasPerpendicularContainingBlock) {
2663                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2664                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2665                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2666                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2667             }
2668             return;
2669         }
2670
2671         // FIXME: Account for block-flow in flexible boxes.
2672         // https://bugs.webkit.org/show_bug.cgi?id=46418
2673         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2674         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2675         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2676         bool checkMinMaxHeight = false;
2677
2678         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2679         // grab our cached flexible height.
2680         // FIXME: Account for block-flow in flexible boxes.
2681         // https://bugs.webkit.org/show_bug.cgi?id=46418
2682         if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
2683             h = Length(overrideLogicalContentHeight(), Fixed);
2684         else if (treatAsReplaced)
2685             h = Length(computeReplacedLogicalHeight(), Fixed);
2686         else {
2687             h = style().logicalHeight();
2688             checkMinMaxHeight = true;
2689         }
2690
2691         // Block children of horizontal flexible boxes fill the height of the box.
2692         // FIXME: Account for block-flow in flexible boxes.
2693         // https://bugs.webkit.org/show_bug.cgi?id=46418
2694         if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL
2695                 && parent()->isStretchingChildren()) {
2696             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2697             checkMinMaxHeight = false;
2698         }
2699
2700         LayoutUnit heightResult;
2701         if (checkMinMaxHeight) {
2702             heightResult = computeLogicalHeightUsing(style().logicalHeight());
2703             if (heightResult == -1)
2704                 heightResult = computedValues.m_extent;
2705             heightResult = constrainLogicalHeightByMinMax(heightResult);
2706         } else {
2707             // The only times we don't check min/max height are when a fixed length has
2708             // been given as an override.  Just use that.  The value has already been adjusted
2709             // for box-sizing.
2710             heightResult = h.value() + borderAndPaddingLogicalHeight();
2711         }
2712
2713         computedValues.m_extent = heightResult;
2714         
2715         if (hasPerpendicularContainingBlock) {
2716             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2717             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2718                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2719                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2720         }
2721     }
2722
2723     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2724     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2725     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2726     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2727     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2728     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2729         && (isRoot() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercent())) && !isInline();
2730     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2731         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2732         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2733         if (isRoot())
2734             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2735         else {
2736             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2737             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2738         }
2739     }
2740 }
2741
2742 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height) const
2743 {
2744     LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height);
2745     if (logicalHeight != -1)
2746         logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2747     return logicalHeight;
2748 }
2749
2750 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height) const
2751 {
2752     LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height);
2753     if (heightIncludingScrollbar == -1)
2754         return -1;
2755     return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2756 }
2757
2758 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height) const
2759 {
2760     if (height.isFixed())
2761         return height.value();
2762     if (height.isPercent())
2763         return computePercentageLogicalHeight(height);
2764     return -1;
2765 }
2766
2767 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock, bool isPerpendicularWritingMode) const
2768 {
2769     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2770     // and percent heights of children should be resolved against the multicol or paged container.
2771     if (containingBlock->isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2772         return true;
2773
2774     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2775     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2776     if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2777         return false;
2778     return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2779 }
2780
2781 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2782 {
2783     LayoutUnit availableHeight = -1;
2784     
2785     bool skippedAutoHeightContainingBlock = false;
2786     RenderBlock* cb = containingBlock();
2787     const RenderBox* containingBlockChild = this;
2788     LayoutUnit rootMarginBorderPaddingHeight = 0;
2789     bool isHorizontal = isHorizontalWritingMode();
2790     while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb, isHorizontal != cb->isHorizontalWritingMode())) {
2791         if (cb->isBody() || cb->isRoot())
2792             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2793         skippedAutoHeightContainingBlock = true;
2794         containingBlockChild = cb;
2795         cb = cb->containingBlock();
2796         cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2797     }
2798
2799     const RenderStyle& cbstyle = cb->style();
2800
2801     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2802     // explicitly specified that can be used for any percentage computations.
2803     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2804
2805     bool includeBorderPadding = isTable();
2806
2807     if (isHorizontal != cb->isHorizontalWritingMode())
2808         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2809 #if ENABLE(CSS_GRID_LAYOUT)
2810     else if (hasOverrideContainingBlockLogicalHeight())
2811         availableHeight = overrideContainingBlockContentLogicalHeight();
2812 #endif
2813     else if (cb->isTableCell()) {
2814         if (!skippedAutoHeightContainingBlock) {
2815             // Table cells violate what the CSS spec says to do with heights. Basically we
2816             // don't care if the cell specified a height or not. We just always make ourselves
2817             // be a percentage of the cell's current content height.
2818             if (!cb->hasOverrideHeight()) {
2819                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2820                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2821                 // While we can't get all cases right, we can at least detect when the cell has a specified
2822                 // height or when the table has a specified height. In these cases we want to initially have
2823                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2824                 // to grow to fill the space. This could end up being wrong in some cases, but it is
2825                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2826                 RenderTableCell* cell = toRenderTableCell(cb);
2827                 if (scrollsOverflowY() && (!cell->style().logicalHeight().isAuto() || !cell->table()->style().logicalHeight().isAuto()))
2828                     return 0;
2829                 return -1;
2830             }
2831             availableHeight = cb->overrideLogicalContentHeight();
2832             includeBorderPadding = true;
2833         }
2834     } else if (cbstyle.logicalHeight().isFixed()) {
2835         LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle.logicalHeight().value());
2836         availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight()));
2837     } else if (cbstyle.logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2838         // We need to recur and compute the percentage height for our containing block.
2839         LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight());
2840         if (heightWithScrollbar != -1) {
2841             LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2842             // We need to adjust for min/max height because this method does not
2843             // handle the min/max of the current block, its caller does. So the
2844             // return value from the recursive call will not have been adjusted
2845             // yet.
2846             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight());
2847             availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2848         }
2849     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2850         // Don't allow this to affect the block' height() member variable, since this
2851         // can get called while the block is still laying out its kids.
2852         LogicalExtentComputedValues computedValues;
2853         cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2854         availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2855     } else if (cb->isRenderView())
2856         availableHeight = view().pageOrViewLogicalHeight();
2857
2858     if (availableHeight == -1)
2859         return availableHeight;
2860
2861     availableHeight -= rootMarginBorderPaddingHeight;
2862
2863     LayoutUnit result = valueForLength(height, availableHeight);
2864     if (includeBorderPadding) {
2865         // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2866         // It is necessary to use the border-box to match WinIE's broken
2867         // box model. This is essential for sizing inside
2868         // table cells using percentage heights.
2869         result -= borderAndPaddingLogicalHeight();
2870         return std::max<LayoutUnit>(0, result);
2871     }
2872     return result;
2873 }
2874
2875 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2876 {
2877     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style().logicalWidth()), shouldComputePreferred);
2878 }
2879
2880 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2881 {
2882     LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercent()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMinWidth());
2883     LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercent()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMaxWidth());
2884     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2885 }
2886
2887 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2888 {
2889     switch (logicalWidth.type()) {
2890         case Fixed:
2891             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2892         case MinContent:
2893         case MaxContent: {
2894             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2895             LayoutUnit availableLogicalWidth = 0;
2896             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2897         }
2898         case FitContent:
2899         case FillAvailable:
2900         case Percent: 
2901         case Calculated: {
2902             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2903             // containing block's block-flow.
2904             // https://bugs.webkit.org/show_bug.cgi?id=46496
2905             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2906             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2907             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2908             // https://bugs.webkit.org/show_bug.cgi?id=91071
2909             if (logicalWidth.isIntrinsic())
2910                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2911             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2912                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2913         }
2914         FALLTHROUGH;
2915         case Intrinsic:
2916         case MinIntrinsic:
2917         case Auto:
2918         case Relative:
2919         case Undefined:
2920             return intrinsicLogicalWidth();
2921     }
2922
2923     ASSERT_NOT_REACHED();
2924     return 0;
2925 }
2926
2927 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2928 {
2929     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style().logicalHeight()));
2930 }
2931
2932 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2933 {
2934     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style().logicalMinHeight());
2935     LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style().logicalMaxHeight());
2936     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2937 }
2938
2939 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2940 {
2941     switch (logicalHeight.type()) {
2942         case Fixed:
2943             return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2944         case Percent:
2945         case Calculated:
2946         {
2947             auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
2948             while (cb->isAnonymous() && !cb->isRenderView()) {
2949                 cb = cb->containingBlock();
2950                 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2951             }
2952
2953             // FIXME: This calculation is not patched for block-flow yet.
2954             // https://bugs.webkit.org/show_bug.cgi?id=46500
2955             if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
2956                 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2957                 RenderBlock* block = toRenderBlock(cb);
2958                 LogicalExtentComputedValues computedValues;
2959                 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2960                 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2961                 LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2962                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2963             }
2964             
2965             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2966             // containing block's block-flow.
2967             // https://bugs.webkit.org/show_bug.cgi?id=46496
2968             LayoutUnit availableHeight;
2969             if (isOutOfFlowPositioned())
2970                 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2971             else {
2972                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
2973                 // It is necessary to use the border-box to match WinIE's broken
2974                 // box model.  This is essential for sizing inside
2975                 // table cells using percentage heights.
2976                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
2977                 // https://bugs.webkit.org/show_bug.cgi?id=46997
2978                 while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercent())) {
2979                     if (cb->isTableCell()) {
2980                         // Don't let table cells squeeze percent-height replaced elements
2981                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2982                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
2983                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2984                     }
2985                     toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2986                     cb = cb->containingBlock();
2987                 }
2988             }
2989             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
2990         }
2991         default:
2992             return intrinsicLogicalHeight();
2993     }
2994 }
2995
2996 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
2997 {
2998     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType));
2999 }
3000
3001 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3002 {
3003     // We need to stop here, since we don't want to increase the height of the table
3004     // artificially.  We're going to rely on this cell getting expanded to some new
3005     // height, and then when we lay out again we'll use the calculation below.
3006     if (isTableCell() && (h.isAuto() || h.isPercent())) {
3007         if (hasOverrideHeight())
3008             return overrideLogicalContentHeight();
3009         return logicalHeight() - borderAndPaddingLogicalHeight();
3010     }
3011
3012     if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3013         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3014         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
3015         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3016     }
3017
3018     LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h);
3019     if (heightIncludingScrollbar != -1)
3020         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3021
3022     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3023     // https://bugs.webkit.org/show_bug.cgi?id=46500
3024     if (isRenderBlock() && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3025         RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
3026         LogicalExtentComputedValues computedValues;
3027         block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
3028         LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
3029         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3030     }
3031
3032     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3033     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3034     if (heightType == ExcludeMarginBorderPadding) {
3035         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3036         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3037     }
3038     return availableHeight;
3039 }
3040
3041 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3042 {
3043     if (isTableCell()) {
3044         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3045         // we may just do it with an extra anonymous block inside the cell.
3046         marginBefore = 0;
3047         marginAfter = 0;
3048         return;
3049     }
3050
3051     // Margins are calculated with respect to the logical width of
3052     // the containing block (8.3)
3053     LayoutUnit cw = containingBlockLogicalWidthForContent();
3054     const RenderStyle& containingBlockStyle = containingBlock->style();
3055     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3056     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3057 }
3058
3059 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
3060 {
3061     LayoutUnit marginBefore;
3062     LayoutUnit marginAfter;
3063     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3064     containingBlock->setMarginBeforeForChild(*this, marginBefore);
3065     containingBlock->setMarginAfterForChild(*this, marginAfter);
3066 }
3067
3068 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3069 {
3070     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3071         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3072
3073     if (containingBlock->isBox()) {
3074         bool isFixedPosition = style().position() == FixedPosition;
3075
3076         RenderFlowThread* flowThread = flowThreadContainingBlock();
3077         if (!flowThread) {
3078             if (isFixedPosition && containingBlock->isRenderView())
3079                 return toRenderView(containingBlock)->clientLogicalWidthForFixedPosition();
3080
3081             return toRenderBox(containingBlock)->clientLogicalWidth();
3082         }
3083
3084         if (isFixedPosition && containingBlock->isRenderNamedFlowThread())
3085             return containingBlock->view().clientLogicalWidth();
3086
3087         if (!containingBlock->isRenderBlock())
3088             return toRenderBox(*containingBlock).clientLogicalWidth();
3089
3090         const RenderBlock* cb = toRenderBlock(containingBlock);
3091         RenderBoxRegionInfo* boxInfo = 0;
3092         if (!region) {
3093             if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
3094                 return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
3095             if (isWritingModeRoot()) {
3096                 LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
3097                 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
3098                 if (cbRegion)
3099                     boxInfo = cb->renderBoxRegionInfo(cbRegion);
3100             }
3101         } else if (region && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3102             RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
3103             boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
3104         }
3105         return (boxInfo) ? std::max<LayoutUnit>(0, cb->clientLogicalWidth() - (cb->logicalWidth() - boxInfo->logicalWidth())) : cb->clientLogicalWidth();
3106     }
3107
3108     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
3109
3110     const RenderInline* flow = toRenderInline(containingBlock);
3111     InlineFlowBox* first = flow->firstLineBox();
3112     InlineFlowBox* last = flow->lastLineBox();
3113
3114     // If the containing block is empty, return a width of 0.
3115     if (!first || !last)
3116         return 0;
3117
3118     LayoutUnit fromLeft;
3119     LayoutUnit fromRight;
3120     if (containingBlock->style().isLeftToRightDirection()) {
3121         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3122         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3123     } else {
3124         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3125         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3126     }
3127
3128     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3129 }
3130
3131 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3132 {
3133     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3134         return containingBlockLogicalWidthForPositioned(containingBlock, 0, false);
3135
3136     if (containingBlock->isBox()) {
3137         bool isFixedPosition = style().position() == FixedPosition;
3138
3139         if (isFixedPosition && containingBlock->isRenderView())
3140             return toRenderView(containingBlock)->clientLogicalHeightForFixedPosition();
3141
3142         const RenderBlock* cb = containingBlock->isRenderBlock() ? toRenderBlock(containingBlock) : containingBlock->containingBlock();
3143         LayoutUnit result = cb->clientLogicalHeight();
3144         RenderFlowThread* flowThread = flowThreadContainingBlock();
3145         if (flowThread && containingBlock->isRenderFlowThread() && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3146             if (containingBlock->isRenderNamedFlowThread() && isFixedPosition)
3147                 return containingBlock->view().clientLogicalHeight();
3148             return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
3149         }
3150         return result;
3151     }
3152         
3153     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
3154
3155     const RenderInline* flow = toRenderInline(containingBlock);
3156     InlineFlowBox* first = flow->firstLineBox();
3157     InlineFlowBox* last = flow->lastLineBox();
3158
3159     // If the containing block is empty, return a height of 0.
3160     if (!first || !last)
3161         return 0;
3162
3163     LayoutUnit heightResult;
3164     LayoutRect boundingBox = flow->linesBoundingBox();
3165     if (containingBlock->isHorizontalWritingMode())
3166         heightResult = boundingBox.height();
3167     else
3168         heightResult = boundingBox.width();
3169     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3170     return heightResult;
3171 }
3172
3173 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3174 {
3175     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3176         return;
3177
3178     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3179     if (child->parent()->style().direction() == LTR) {
3180         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3181         for (auto curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3182             if (curr->isBox()) {
3183                 staticPosition += toRenderBox(curr)->logicalLeft();
3184                 if (region && toRenderBox(curr)->isRenderBlock()) {
3185                     const RenderBlock* cb = toRenderBlock(curr);
3186                     region = cb->clampToStartAndEndRegions(region);
3187                     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
3188                     if (boxInfo)
3189                         staticPosition += boxInfo->logicalLeft();
3190                 }
3191             }
3192         }
3193         logicalLeft.setValue(Fixed, staticPosition);
3194     } else {
3195         RenderBox& enclosingBox = child->parent()->enclosingBox();
3196         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3197         for (RenderElement* curr = &enclosingBox; curr; curr = curr->container()) {
3198             if (curr->isBox()) {
3199                 if (curr != containerBlock)
3200                     staticPosition -= toRenderBox(curr)->logicalLeft();
3201                 if (curr == &enclosingBox)
3202                     staticPosition -= enclosingBox.logicalWidth();
3203                 if (region && curr->isRenderBlock()) {
3204                     const RenderBlock* cb = toRenderBlock(curr);
3205                     region = cb->clampToStartAndEndRegions(region);
3206                     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
3207                     if (boxInfo) {
3208                         if (curr != containerBlock)
3209                             staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3210                         if (curr == &enclosingBox)
3211                             staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3212                     }
3213                 }
3214             }
3215             if (curr == containerBlock)
3216                 break;
3217         }
3218         logicalRight.setValue(Fixed, staticPosition);
3219     }
3220 }
3221
3222 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3223 {
3224     if (isReplaced()) {
3225         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3226         // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3227         computePositionedLogicalWidthReplaced(computedValues);
3228         return;
3229     }
3230
3231     // QUESTIONS
3232     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3233     // the type 'static' in determining whether to calculate the static distance?
3234     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3235
3236     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3237     // than or less than the computed width().  Be careful of box-sizing and
3238     // percentage issues.
3239
3240     // The following is based off of the W3C Working Draft from April 11, 2006 of
3241     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3242     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3243     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3244     // correspond to text from the spec)
3245
3246
3247     // We don't use containingBlock(), since we may be positioned by an enclosing
3248     // relative positioned inline.
3249     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3250     
3251     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3252
3253     // Use the container block's direction except when calculating the static distance
3254     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3255     // of the CSS 2.1 test suite
3256     TextDirection containerDirection = containerBlock->style().direction();
3257
3258     bool isHorizontal = isHorizontalWritingMode();
3259     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3260     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3261     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3262
3263     Length logicalLeftLength = style().logicalLeft();
3264     Length logicalRightLength = style().logicalRight();
3265
3266     /*---------------------------------------------------------------------------*\
3267      * For the purposes of this section and the next, the term "static position"
3268      * (of an element) refers, roughly, to the position an element would have had
3269      * in the normal flow. More precisely:
3270      *
3271      * * The static position for 'left' is the distance from the left edge of the
3272      *   containing block to the left margin edge of a hypothetical box that would
3273      *   have been the first box of the element if its 'position' property had
3274      *   been 'static' and 'float' had been 'none'. The value is negative if the
3275      *   hypothetical box is to the left of the containing block.
3276      * * The static position for 'right' is the distance from the right edge of the
3277      *   containing block to the right margin edge of the same hypothetical box as
3278      *   above. The value is positive if the hypothetical box is to the left of the
3279      *   containing block's edge.
3280      *
3281      * But rather than actually calculating the dimensions of that hypothetical box,
3282      * user agents are free to make a guess at its probable position.
3283      *
3284      * For the purposes of calculating the static position, the containing block of
3285      * fixed positioned elements is the initial containing block instead of the
3286      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3287      * origin.
3288     \*---------------------------------------------------------------------------*/
3289
3290     // see FIXME 1
3291     // Calculate the static distance if needed.
3292     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3293     
3294     // Calculate constraint equation values for 'width' case.
3295     computePositionedLogicalWidthUsing(style().logicalWidth(), containerBlock, containerDirection,
3296                                        containerLogicalWidth, bordersPlusPadding,
3297                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3298                                        computedValues);
3299
3300     // Calculate constraint equation values for 'max-width' case.
3301     if (!style().logicalMaxWidth().isUndefined()) {
3302         LogicalExtentComputedValues maxValues;
3303
3304         computePositionedLogicalWidthUsing(style().logicalMaxWidth(), containerBlock, containerDirection,
3305                                            containerLogicalWidth, bordersPlusPadding,
3306                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3307                                            maxValues);
3308
3309         if (computedValues.m_extent > maxValues.m_extent) {
3310             computedValues.m_extent = maxValues.m_extent;
3311             computedValues.m_position = maxValues.m_position;
3312             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3313             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3314         }
3315     }
3316
3317     // Calculate constraint equation values for 'min-width' case.
3318     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3319         LogicalExtentComputedValues minValues;
3320
3321         computePositionedLogicalWidthUsing(style().logicalMinWidth(), containerBlock, containerDirection,
3322                                            containerLogicalWidth, bordersPlusPadding,
3323                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3324                                            minValues);
3325
3326         if (computedValues.m_extent < minValues.m_extent) {
3327             computedValues.m_extent = minValues.m_extent;
3328             computedValues.m_position = minValues.m_position;
3329             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3330             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3331         }
3332     }
3333
3334     computedValues.m_extent += bordersPlusPadding;
3335     
3336     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3337     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3338     RenderFlowThread* flowThread = flowThreadContainingBlock();
3339     if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) {
3340         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3341         LayoutUnit logicalLeftPos = computedValues.m_position;
3342         const RenderBlock* cb = toRenderBlock(containerBlock);
3343         LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
3344         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
3345         if (cbRegion) {
3346             RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
3347             if (boxInfo) {
3348                 logicalLeftPos += boxInfo->logicalLeft();
3349                 computedValues.m_position = logicalLeftPos;
3350             }
3351         }
3352     }
3353 }
3354
3355 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
3356 {
3357     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3358     // 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.
3359     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style().isFlippedBlocksWritingMode()) {
3360         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3361         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
3362     } else
3363         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
3364 }
3365
3366 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
3367                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3368                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3369                                                    LogicalExtentComputedValues& computedValues) const
3370 {
3371     if (logicalWidth.isIntrinsic())
3372         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3373
3374     // 'left' and 'right' cannot both be 'auto' because one would of been
3375     // converted to the static position already
3376     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3377
3378     LayoutUnit logicalLeftValue = 0;
3379
3380     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
3381
3382     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3383     bool logicalLeftIsAuto = logicalLeft.isAuto();
3384     bool logicalRightIsAuto = logicalRight.isAuto();
3385     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3386     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3387
3388     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3389         /*-----------------------------------------------------------------------*\
3390          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3391          * right' are 'auto', solve the equation under the extra constraint that
3392          * the two margins get equal values, unless this would make them negative,
3393          * in which case when direction of the containing block is 'ltr' ('rtl'),
3394          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3395          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3396          * solve the equation for that value. If the values are over-constrained,
3397          * ignore the value for 'left' (in case the 'direction' property of the
3398          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3399          * and solve for that value.
3400         \*-----------------------------------------------------------------------*/
3401         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3402         // case because the value is not used for any further calculations.
3403
3404         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3405         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3406
3407         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3408
3409         // Margins are now the only unknown
3410         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3411             // Both margins auto, solve for equality
3412             if (availableSpace >= 0) {
3413                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3414                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3415             } else {
3416                 // Use the containing block's direction rather than the parent block's
3417                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3418                 if (containerDirection == LTR) {
3419                     marginLogicalLeftValue = 0;
3420                     marginLogicalRightValue = availableSpace; // will be negative
3421                 } else {
3422                     marginLogicalLeftValue = availableSpace; // will be negative
3423                     marginLogicalRightValue = 0;
3424                 }
3425             }
3426         } else if (marginLogicalLeft.isAuto()) {
3427             // Solve for left margin
3428             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3429             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3430         } else if (marginLogicalRight.isAuto()) {
3431             // Solve for right margin
3432             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3433             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3434         } else {
3435             // Over-constrained, solve for left if direction is RTL
3436             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3437             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3438
3439             // Use the containing block's direction rather than the parent block's
3440             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3441             if (containerDirection == RTL)
3442                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3443         }
3444     } else {
3445         /*--------------------------------------------------------------------*\
3446          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3447          * to 0, and pick the one of the following six rules that applies.
3448          *
3449          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3450          *    width is shrink-to-fit. Then solve for 'left'
3451          *
3452          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3453          * ------------------------------------------------------------------
3454          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3455          *    the 'direction' property of the containing block is 'ltr' set
3456          *    'left' to the static position, otherwise set 'right' to the
3457          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3458          *    or 'right' (if 'direction' is 'ltr').
3459          * ------------------------------------------------------------------
3460          *
3461          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3462          *    width is shrink-to-fit . Then solve for 'right'
3463          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3464          *    for 'left'
3465          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3466          *    for 'width'
3467          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3468          *    for 'right'
3469          *
3470          * Calculation of the shrink-to-fit width is similar to calculating the
3471          * width of a table cell using the automatic table layout algorithm.
3472          * Roughly: calculate the preferred width by formatting the content
3473          * without breaking lines other than where explicit line breaks occur,
3474          * and also calculate the preferred minimum width, e.g., by trying all
3475          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3476          * Thirdly, calculate the available width: this is found by solving
3477          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3478          * to 0.
3479          *
3480          * Then the shrink-to-fit width is:
3481          * min(max(preferred minimum width, available width), preferred width).
3482         \*--------------------------------------------------------------------*/
3483         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3484         // because the value is not used for any further calculations.
3485
3486         // Calculate margins, 'auto' margins are ignored.
3487         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3488         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3489
3490         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3491
3492         // FIXME: Is there a faster way to find the correct case?
3493         // Use rule/case that applies.
3494         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3495             // RULE 1: (use shrink-to-fit for width, and solve of left)
3496             LayoutUnit logicalRightValue = valueForLength(logicalRight, 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 - logicalRightValue;
3502             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3503             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3504         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3505             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3506             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3507
3508             // FIXME: would it be better to have shrink-to-fit in one step?
3509             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3510             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3511             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3512             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3513         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3514             // RULE 4: (solve for left)
3515             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3516             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3517         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3518             // RULE 5: (solve for width)
3519             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3520             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3521         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3522             // RULE 6: (no need solve for right)
3523             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3524             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3525         }
3526     }
3527
3528     // Use computed values to calculate the horizontal position.
3529
3530     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3531     // positioned, inline because right now, it is using the logical left position
3532     // of the first line box when really it should use the last line box.  When
3533     // this is fixed elsewhere, this block should be removed.
3534     if (containerBlock->isRenderInline() && !containerBlock->style().isLeftToRightDirection()) {
3535         const RenderInline* flow = toRenderInline(containerBlock);
3536         InlineFlowBox* firstLine = flow->firstLineBox();
3537         InlineFlowBox* lastLine = flow->lastLineBox();
3538         if (firstLine && lastLine && firstLine != lastLine) {
3539             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3540             return;
3541         }
3542     }
3543
3544     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3545     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3546 }
3547
3548 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3549 {
3550     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3551         return;
3552     
3553     // FIXME: The static distance computation has not been patched for mixed writing modes.
3554     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3555     for (RenderElement* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3556         if (curr->isBox() && !curr->isTableRow())
3557             staticLogicalTop += toRenderBox(curr)->logicalTop();
3558     }
3559     logicalTop.setValue(Fixed, staticLogicalTop);
3560 }
3561
3562 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3563 {
3564     if (isReplaced()) {
3565         computePositionedLogicalHeightReplaced(computedValues);
3566         return;
3567     }
3568
3569     // The following is based off of the W3C Working Draft from April 11, 2006 of
3570     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3571     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3572     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3573     // correspond to text from the spec)
3574
3575
3576     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3577     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3578
3579     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3580
3581     const RenderStyle& styleToUse = style();
3582     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3583     const Length marginBefore = styleToUse.marginBefore();
3584     const Length marginAfter = styleToUse.marginAfter();
3585     Length logicalTopLength = styleToUse.logicalTop();
3586     Length logicalBottomLength = styleToUse.logicalBottom();
3587
3588     /*---------------------------------------------------------------------------*\
3589      * For the purposes of this section and the next, the term "static position"
3590      * (of an element) refers, roughly, to the position an element would have had
3591      * in the normal flow. More precisely, the static position for 'top' is the
3592      * distance from the top edge of the containing block to the top margin edge
3593      * of a hypothetical box that would have been the first box of the element if
3594      * its 'position' property had been 'static' and 'float' had been 'none'. The
3595      * value is negative if the hypothetical box is above the containing block.
3596      *
3597      * But rather than actually calculating the dimensions of that hypothetical
3598      * box, user agents are free to make a guess at its probable position.
3599      *
3600      * For the purposes of calculating the static position, the containing block
3601      * of fixed positioned elements is the initial containing block instead of
3602      * the viewport.
3603     \*---------------------------------------------------------------------------*/
3604
3605     // see FIXME 1
3606     // Calculate the static distance if needed.
3607     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3608
3609     // Calculate constraint equation values for 'height' case.
3610     LayoutUnit logicalHeight = computedValues.m_extent;
3611     computePositionedLogicalHeightUsing(styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3612                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3613                                         computedValues);
3614
3615     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3616     // see FIXME 2
3617
3618     // Calculate constraint equation values for 'max-height' case.
3619     if (!styleToUse.logicalMaxHeight().isUndefined()) {
3620         LogicalExtentComputedValues maxValues;
3621
3622         computePositionedLogicalHeightUsing(styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3623                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3624                                             maxValues);
3625
3626         if (computedValues.m_extent > maxValues.m_extent) {
3627             computedValues.m_extent = maxValues.m_extent;
3628             computedValues.m_position = maxValues.m_position;
3629             computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3630             computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3631         }
3632     }
3633
3634     // Calculate constraint equation values for 'min-height' case.
3635     if (!styleToUse.logicalMinHeight().isZero()) {
3636         LogicalExtentComputedValues minValues;
3637
3638         computePositionedLogicalHeightUsing(styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3639                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3640                                             minValues);
3641
3642         if (computedValues.m_extent < minValues.m_extent) {
3643             computedValues.m_extent = minValues.m_extent;
3644             computedValues.m_position = minValues.m_position;
3645             computedValues.m_margins.m_before = minValues.m_margins.m_before;
3646             computedValues.m_margins.m_after = minValues.m_margins.m_after;
3647         }
3648     }
3649
3650     // Set final height value.
3651     computedValues.m_extent += bordersPlusPadding;
3652     
3653     // Adjust logicalTop if we need to for perpendicular writing modes in regions.
3654     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3655     RenderFlowThread* flowThread = flowThreadContainingBlock();
3656     if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) {
3657         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3658         LayoutUnit logicalTopPos = computedValues.m_position;
3659         const RenderBlock* cb = toRenderBlock(containerBlock);
3660         LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft();
3661         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
3662         if (cbRegion) {
3663             RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
3664             if (boxInfo) {
3665                 logicalTopPos += boxInfo->logicalLeft();
3666                 computedValues.m_position = logicalTopPos;
3667             }
3668         }
3669     }
3670 }
3671
3672 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3673 {
3674     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3675     // 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.
3676     if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3677         || (child->style().isFlippedBlocksWritingMode() != containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3678         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3679
3680     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3681     if (containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3682         if (child->isHorizontalWritingMode())
3683             logicalTopPos += containerBlock->borderBottom();
3684         else
3685             logicalTopPos += containerBlock->borderRight();
3686     } else {
3687         if (child->isHorizontalWritingMode())
3688             logicalTopPos += containerBlock->borderTop();
3689         else
3690             logicalTopPos += containerBlock->borderLeft();
3691     }
3692 }
3693
3694 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3695                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3696                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
3697                                                     LogicalExtentComputedValues& computedValues) const
3698 {
3699     // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3700     // converted to the static position in computePositionedLogicalHeight()
3701     ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3702
3703     LayoutUnit logicalHeightValue;
3704     LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
3705
3706     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
3707
3708     LayoutUnit logicalTopValue = 0;
3709     LayoutUnit resolvedLogicalHeight = 0;
3710
3711     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3712     bool logicalTopIsAuto = logicalTop.isAuto();
3713     bool logicalBottomIsAuto = logicalBottom.isAuto();
3714
3715     // Height is never unsolved for tables.
3716     if (isTable()) {
3717         resolvedLogicalHeight = contentLogicalHeight;
3718         logicalHeightIsAuto = false;
3719     } else
3720         resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
3721
3722     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3723         /*-----------------------------------------------------------------------*\
3724          * If none of the three are 'auto': If both 'margin-top' and 'margin-
3725          * bottom' are 'auto', solve the equation under the extra constraint that
3726          * the two margins get equal values. If one of 'margin-top' or 'margin-
3727          * bottom' is 'auto', solve the equation for that value. If the values
3728          * are over-constrained, ignore the value for 'bottom' and solve for that
3729          * value.
3730         \*-----------------------------------------------------------------------*/
3731         // NOTE:  It is not necessary to solve for 'bottom' in the over constrained
3732         // case because the value is not used for any further calculations.
3733
3734         logicalHeightValue = resolvedLogicalHeight;
3735         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3736
3737         const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
3738
3739         // Margins are now the only unknown
3740         if (marginBefore.isAuto() && marginAfter.isAuto()) {
3741             // Both margins auto, solve for equality
3742             // NOTE: This may result in negative values.
3743             computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3744             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3745         } else if (marginBefore.isAuto()) {
3746             // Solve for top margin
3747             computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3748             computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3749         } else if (marginAfter.isAuto()) {
3750             // Solve for bottom margin
3751             computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3752             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3753         } else {
3754             // Over-constrained, (no need solve for bottom)
3755             computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3756             computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3757         }
3758     } else {
3759         /*--------------------------------------------------------------------*\
3760          * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3761          * to 0, and pick the one of the following six rules that applies.
3762          *
3763          * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3764          *    the height is based on the content, and solve for 'top'.
3765          *
3766          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3767          * ------------------------------------------------------------------
3768          * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3769          *    set 'top' to the static position, and solve for 'bottom'.
3770          * ------------------------------------------------------------------
3771          *
3772          * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3773          *    the height is based on the content, and solve for 'bottom'.
3774          * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3775          *    solve for 'top'.
3776          * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3777          *    solve for 'height'.
3778          * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3779          *    solve for 'bottom'.
3780         \*--------------------------------------------------------------------*/
3781         // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3782         // because the value is not used for any further calculations.
3783
3784         // Calculate margins, 'auto' margins are ignored.
3785         computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
3786         computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);
3787
3788         const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
3789
3790         // Use rule/case that applies.
3791         if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {