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