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