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