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