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