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