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