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