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