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