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