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