diff options
author | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-06-27 06:07:23 +0000 |
---|---|---|
committer | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-06-27 06:07:23 +0000 |
commit | 1bf1084f2b10c3b47fd1a588d85d21ed0eb41d0c (patch) | |
tree | 46dcd36c86e7fbc6e5df36deb463b33e9967a6f7 /Source/WebCore/rendering/RenderBox.cpp | |
parent | 32761a6cee1d0dee366b885b7b9c777e67885688 (diff) | |
download | WebKitGtk-tarball-master.tar.gz |
webkitgtk-2.16.5HEADwebkitgtk-2.16.5master
Diffstat (limited to 'Source/WebCore/rendering/RenderBox.cpp')
-rw-r--r-- | Source/WebCore/rendering/RenderBox.cpp | 2320 |
1 files changed, 1361 insertions, 959 deletions
diff --git a/Source/WebCore/rendering/RenderBox.cpp b/Source/WebCore/rendering/RenderBox.cpp index f42232d54..26ce88896 100644 --- a/Source/WebCore/rendering/RenderBox.cpp +++ b/Source/WebCore/rendering/RenderBox.cpp @@ -3,7 +3,7 @@ * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com) * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com) - * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. + * Copyright (C) 2005-2010, 2015 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -25,43 +25,54 @@ #include "config.h" #include "RenderBox.h" -#include "Chrome.h" -#include "ChromeClient.h" +#include "CSSFontSelector.h" +#include "ControlStates.h" #include "Document.h" #include "EventHandler.h" #include "FloatQuad.h" +#include "FloatRoundedRect.h" #include "Frame.h" #include "FrameView.h" #include "GraphicsContext.h" -#include "HTMLElement.h" +#include "HTMLBodyElement.h" +#include "HTMLButtonElement.h" #include "HTMLFrameOwnerElement.h" +#include "HTMLHtmlElement.h" #include "HTMLInputElement.h" +#include "HTMLLegendElement.h" #include "HTMLNames.h" +#include "HTMLSelectElement.h" #include "HTMLTextAreaElement.h" #include "HitTestResult.h" #include "InlineElementBox.h" +#include "MainFrame.h" #include "Page.h" #include "PaintInfo.h" #include "RenderBoxRegionInfo.h" +#include "RenderChildIterator.h" +#include "RenderDeprecatedFlexibleBox.h" #include "RenderFlexibleBox.h" -#include "RenderFlowThread.h" #include "RenderGeometryMap.h" #include "RenderInline.h" #include "RenderIterator.h" #include "RenderLayer.h" -#include "RenderRegion.h" +#include "RenderLayerCompositor.h" +#include "RenderMultiColumnFlowThread.h" +#include "RenderNamedFlowFragment.h" +#include "RenderNamedFlowThread.h" #include "RenderTableCell.h" #include "RenderTheme.h" #include "RenderView.h" +#include "ScrollAnimator.h" +#include "ScrollbarTheme.h" +#include "StyleScrollSnapPoints.h" #include "TransformState.h" #include "htmlediting.h" #include <algorithm> #include <math.h> #include <wtf/StackStats.h> -#if USE(ACCELERATED_COMPOSITING) -#include "RenderLayerCompositor.h" -#endif +#include "RenderGrid.h" #if PLATFORM(IOS) #include "Settings.h" @@ -69,56 +80,90 @@ namespace WebCore { +struct SameSizeAsRenderBox : public RenderBoxModelObject { + virtual ~SameSizeAsRenderBox() { } + LayoutRect frameRect; + LayoutBoxExtent marginBox; + LayoutUnit preferredLogicalWidths[2]; + void* pointers[2]; +}; + +COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small); + using namespace HTMLNames; // Used by flexible boxes when flexing this element and by table cells. typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap; -static OverrideSizeMap* gOverrideHeightMap = 0; -static OverrideSizeMap* gOverrideWidthMap = 0; +static OverrideSizeMap* gOverrideHeightMap = nullptr; +static OverrideSizeMap* gOverrideWidthMap = nullptr; // Used by grid elements to properly size their grid items. -static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0; -static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0; - +typedef WTF::HashMap<const RenderBox*, std::optional<LayoutUnit>> OverrideOptionalSizeMap; +static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr; +static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr; +static OverrideSizeMap* gExtraInlineOffsetMap = nullptr; +static OverrideSizeMap* gExtraBlockOffsetMap = nullptr; // Size of border belt for autoscroll. When mouse pointer in border belt, // autoscroll is started. static const int autoscrollBeltSize = 20; static const unsigned backgroundObscurationTestMaxDepth = 4; -bool RenderBox::s_hadOverflowClip = false; +using ControlStatesRendererMap = HashMap<const RenderObject*, std::unique_ptr<ControlStates>>; +static ControlStatesRendererMap& controlStatesRendererMap() +{ + static NeverDestroyed<ControlStatesRendererMap> map; + return map; +} -static bool skipBodyBackground(const RenderBox* bodyElementRenderer) +static ControlStates* controlStatesForRenderer(const RenderBox& renderer) { - ASSERT(bodyElementRenderer->isBody()); - // The <body> only paints its background if the root element has defined a background independent of the body, - // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject). - auto documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer(); - return documentElementRenderer - && !documentElementRenderer->hasBackground() - && (documentElementRenderer == bodyElementRenderer->parent()); + return controlStatesRendererMap().ensure(&renderer, [] { + return std::make_unique<ControlStates>(); + }).iterator->value.get(); } -RenderBox::RenderBox(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags) - : RenderBoxModelObject(element, std::move(style), baseTypeFlags) - , m_minPreferredLogicalWidth(-1) - , m_maxPreferredLogicalWidth(-1) - , m_inlineBoxWrapper(0) +static void removeControlStatesForRenderer(const RenderBox& renderer) +{ + controlStatesRendererMap().remove(&renderer); +} + +bool RenderBox::s_hadOverflowClip = false; + +RenderBox::RenderBox(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags) + : RenderBoxModelObject(element, WTFMove(style), baseTypeFlags) { setIsBox(); } -RenderBox::RenderBox(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags) - : RenderBoxModelObject(document, std::move(style), baseTypeFlags) - , m_minPreferredLogicalWidth(-1) - , m_maxPreferredLogicalWidth(-1) - , m_inlineBoxWrapper(0) +RenderBox::RenderBox(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags) + : RenderBoxModelObject(document, WTFMove(style), baseTypeFlags) { setIsBox(); } RenderBox::~RenderBox() { + // Do not add any code here. Add it to willBeDestroyed() instead. +} + +void RenderBox::willBeDestroyed() +{ + if (frame().eventHandler().autoscrollRenderer() == this) + frame().eventHandler().stopAutoscrollTimer(true); + + clearOverrideSize(); + clearContainingBlockOverrideSize(); + clearExtraInlineAndBlockOffests(); + + RenderBlock::removePercentHeightDescendantIfNeeded(*this); + + ShapeOutsideInfo::removeInfo(*this); + + view().unscheduleLazyRepaint(*this); + removeControlStatesForRenderer(*this); + + RenderBoxModelObject::willBeDestroyed(); } RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const @@ -133,18 +178,28 @@ RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const // logical top or logical bottom of the block to size as though the border box in the first and // last regions extended infinitely. Otherwise the lines are going to size according to the regions // they overflow into, which makes no sense when this block doesn't exist in |region| at all. - RenderRegion* startRegion = 0; - RenderRegion* endRegion = 0; - flowThread->getRegionRangeForBox(this, startRegion, endRegion); + RenderRegion* startRegion = nullptr; + RenderRegion* endRegion = nullptr; + if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) + return region; - if (startRegion && region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent()) + if (region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent()) return startRegion; - if (endRegion && region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent()) + if (region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent()) return endRegion; return region; } +bool RenderBox::hasRegionRangeInFlowThread() const +{ + RenderFlowThread* flowThread = flowThreadContainingBlock(); + if (!flowThread || !flowThread->hasValidRegionInfo()) + return false; + + return flowThread->hasCachedRegionRangeForBox(*this); +} + LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const { if (!region) @@ -162,17 +217,16 @@ LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegio if (!region) return borderBoxRect(); - RenderFlowThread* flowThread = flowThreadContainingBlock(); - if (!flowThread) + auto* flowThread = flowThreadContainingBlock(); + if (!is<RenderNamedFlowThread>(flowThread)) return borderBoxRect(); - RenderRegion* startRegion = 0; - RenderRegion* endRegion = 0; - flowThread->getRegionRangeForBox(this, startRegion, endRegion); - - // FIXME: In a perfect world this condition should never happen. - if (!startRegion || !endRegion) + RenderRegion* startRegion = nullptr; + RenderRegion* endRegion = nullptr; + if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) { + // FIXME: In a perfect world this condition should never happen. return borderBoxRect(); + } ASSERT(flowThread->regionInRange(region, startRegion, endRegion)); @@ -184,21 +238,28 @@ LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegio // We have cached insets. LayoutUnit logicalWidth = boxInfo->logicalWidth(); LayoutUnit logicalLeft = boxInfo->logicalLeft(); - + // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts. // FIXME: Doesn't work right with perpendicular writing modes. const RenderBlock* currentBox = containingBlock(); - RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region); + RenderBoxRegionInfo* currentBoxInfo = isRenderFlowThread() ? nullptr : currentBox->renderBoxRegionInfo(region); while (currentBoxInfo && currentBoxInfo->isShifted()) { if (currentBox->style().direction() == LTR) logicalLeft += currentBoxInfo->logicalLeft(); else logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft(); + + // Once we reach the fragmentation container we should stop. + if (currentBox->isRenderFlowThread()) + break; + currentBox = currentBox->containingBlock(); + if (!currentBox) + break; region = currentBox->clampToStartAndEndRegions(region); currentBoxInfo = currentBox->renderBoxRegionInfo(region); } - + if (cacheFlag == DoNotCacheRenderBoxRegionInfo) delete boxInfo; @@ -207,41 +268,14 @@ LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegio return LayoutRect(0, logicalLeft, width(), logicalWidth); } -void RenderBox::clearRenderBoxRegionInfo() -{ - if (isRenderFlowThread()) - return; - - RenderFlowThread* flowThread = flowThreadContainingBlock(); - if (flowThread) - flowThread->removeRenderBoxRegionInfo(this); -} - -void RenderBox::willBeDestroyed() +static RenderBlockFlow* outermostBlockContainingFloatingObject(RenderBox& box) { - if (frame().eventHandler().autoscrollRenderer() == this) - frame().eventHandler().stopAutoscrollTimer(true); - - clearOverrideSize(); - clearContainingBlockOverrideSize(); - - RenderBlock::removePercentHeightDescendantIfNeeded(*this); - -#if ENABLE(CSS_SHAPES) - ShapeOutsideInfo::removeInfo(*this); -#endif - - RenderBoxModelObject::willBeDestroyed(); -} - -RenderBlockFlow* RenderBox::outermostBlockContainingFloatingObject() -{ - ASSERT(isFloating()); + ASSERT(box.isFloating()); RenderBlockFlow* parentBlock = nullptr; - for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(*this)) { + for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(box)) { if (ancestor.isRenderView()) break; - if (!parentBlock || ancestor.containsFloat(*this)) + if (!parentBlock || ancestor.containsFloat(box)) parentBlock = &ancestor; } return parentBlock; @@ -251,11 +285,11 @@ void RenderBox::removeFloatingOrPositionedChildFromBlockLists() { ASSERT(isFloatingOrOutOfFlowPositioned()); - if (documentBeingDestroyed()) + if (renderTreeBeingDestroyed()) return; if (isFloating()) { - if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject()) { + if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject(*this)) { parentBlock->markSiblingsWithFloatsForLayout(this); parentBlock->markAllDescendantsWithFloatsForLayout(this, false); } @@ -273,12 +307,10 @@ void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyl if (oldStyle) { // The background of the root element or the body element could propagate up to // the canvas. Issue full repaint, when our style changes substantially. - if (diff >= StyleDifferenceRepaint && (isRoot() || isBody())) { + if (diff >= StyleDifferenceRepaint && (isDocumentElementRenderer() || isBody())) { view().repaintRootContents(); -#if USE(ACCELERATED_COMPOSITING) if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground()) view().compositor().rootFixedBackgroundsChanged(); -#endif } // When a layout hint happens and an object's position style changes, we have to do a layout @@ -295,6 +327,16 @@ void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyl } else if (isBody()) view().repaintRootContents(); +#if ENABLE(CSS_SCROLL_SNAP) + bool boxContributesSnapPositions = newStyle.scrollSnapArea().hasSnapPosition(); + if (boxContributesSnapPositions || (oldStyle && oldStyle->scrollSnapArea().hasSnapPosition())) { + if (boxContributesSnapPositions) + view().registerBoxWithScrollSnapPositions(*this); + else + view().unregisterBoxWithScrollSnapPositions(*this); + } +#endif + RenderBoxModelObject::styleWillChange(diff, newStyle); } @@ -325,12 +367,12 @@ void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the // new zoomed coordinate space. - if (hasOverflowClip() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) { - if (int left = layer()->scrollXOffset()) { + if (hasOverflowClip() && layer() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) { + if (int left = layer()->scrollOffset().x()) { left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom(); layer()->scrollToXOffset(left); } - if (int top = layer()->scrollYOffset()) { + if (int top = layer()->scrollOffset().y()) { top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom(); layer()->scrollToYOffset(top); } @@ -346,31 +388,36 @@ void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle } bool isBodyRenderer = isBody(); - bool isRootRenderer = isRoot(); - - // Set the text color if we're the body. - if (isBodyRenderer) - document().setTextColor(newStyle.visitedDependentColor(CSSPropertyColor)); + bool isDocElementRenderer = isDocumentElementRenderer(); - if (isRootRenderer || isBodyRenderer) { + if (isDocElementRenderer || isBodyRenderer) { // Propagate the new writing mode and direction up to the RenderView. - RenderStyle& viewStyle = view().style(); - bool viewChangedWritingMode = false; - if (viewStyle.direction() != newStyle.direction() && (isRootRenderer || !document().directionSetOnDocumentElement())) { + auto* documentElementRenderer = document().documentElement()->renderer(); + auto& viewStyle = view().mutableStyle(); + bool rootStyleChanged = false; + bool viewDirectionOrWritingModeChanged = false; + auto* rootRenderer = isBodyRenderer ? documentElementRenderer : nullptr; + if (viewStyle.direction() != newStyle.direction() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetDirection())) { viewStyle.setDirection(newStyle.direction()); - if (isBodyRenderer) - document().documentElement()->renderer()->style().setDirection(newStyle.direction()); + viewDirectionOrWritingModeChanged = true; + if (isBodyRenderer) { + rootRenderer->mutableStyle().setDirection(newStyle.direction()); + rootStyleChanged = true; + } setNeedsLayoutAndPrefWidthsRecalc(); + + view().frameView().topContentDirectionDidChange(); } - if (viewStyle.writingMode() != newStyle.writingMode() && (isRootRenderer || !document().writingModeSetOnDocumentElement())) { + if (viewStyle.writingMode() != newStyle.writingMode() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetWritingMode())) { viewStyle.setWritingMode(newStyle.writingMode()); - viewChangedWritingMode = true; + viewDirectionOrWritingModeChanged = true; view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode()); view().markAllDescendantsWithFloatsForLayout(); if (isBodyRenderer) { - document().documentElement()->renderer()->style().setWritingMode(newStyle.writingMode()); - document().documentElement()->renderer()->setHorizontalWritingMode(newStyle.isHorizontalWritingMode()); + rootStyleChanged = true; + rootRenderer->mutableStyle().setWritingMode(newStyle.writingMode()); + rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode()); } setNeedsLayoutAndPrefWidthsRecalc(); } @@ -378,19 +425,71 @@ void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle view().frameView().recalculateScrollbarOverlayStyle(); const Pagination& pagination = view().frameView().pagination(); - if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) { + if (viewDirectionOrWritingModeChanged && pagination.mode != Pagination::Unpaginated) { viewStyle.setColumnStylesFromPaginationMode(pagination.mode); - if (view().hasColumns() || view().multiColumnFlowThread()) - view().updateColumnProgressionFromStyle(&viewStyle); + if (view().multiColumnFlowThread()) + view().updateColumnProgressionFromStyle(viewStyle); } + + if (viewDirectionOrWritingModeChanged && view().multiColumnFlowThread()) + view().updateStylesForColumnChildren(); + + if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlowThread()) + downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren(); + + if (isBodyRenderer && pagination.mode != Pagination::Unpaginated && page().paginationLineGridEnabled()) { + // Propagate the body font back up to the RenderView and use it as + // the basis of the grid. + if (newStyle.fontDescription() != view().style().fontDescription()) { + view().mutableStyle().setFontDescription(newStyle.fontDescription()); + view().mutableStyle().fontCascade().update(&document().fontSelector()); + } + } + + if (diff != StyleDifferenceEqual) + view().compositor().rootOrBodyStyleChanged(*this, oldStyle); } -#if ENABLE(CSS_SHAPES) - updateShapeOutsideInfoAfterStyleChange(style(), oldStyle); + if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside()) + updateShapeOutsideInfoAfterStyleChange(style(), oldStyle); + updateGridPositionAfterStyleChange(style(), oldStyle); +} + +void RenderBox::willBeRemovedFromTree() +{ +#if ENABLE(CSS_SCROLL_SNAP) + if (hasInitializedStyle() && style().scrollSnapArea().hasSnapPosition()) + view().unregisterBoxWithScrollSnapPositions(*this); #endif + + RenderBoxModelObject::willBeRemovedFromTree(); +} + + +void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle) +{ + if (!oldStyle || !is<RenderGrid>(parent())) + return; + + if (oldStyle->gridItemColumnStart() == style.gridItemColumnStart() + && oldStyle->gridItemColumnEnd() == style.gridItemColumnEnd() + && oldStyle->gridItemRowStart() == style.gridItemRowStart() + && oldStyle->gridItemRowEnd() == style.gridItemRowEnd() + && oldStyle->order() == style.order() + && oldStyle->hasOutOfFlowPosition() == style.hasOutOfFlowPosition()) + return; + + // Positioned items don't participate on the layout of the grid, + // so we don't need to mark the grid as dirty if they change positions. + if (oldStyle->hasOutOfFlowPosition() && style.hasOutOfFlowPosition()) + return; + + // It should be possible to not dirty the grid in some cases (like moving an + // explicitly placed grid item). + // For now, it's more simple to just always recompute the grid. + downcast<RenderGrid>(*parent()).dirtyGrid(); } -#if ENABLE(CSS_SHAPES) void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle) { const ShapeValue* shapeOutside = style.shapeOutside(); @@ -409,53 +508,54 @@ void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, if (!shapeOutside) ShapeOutsideInfo::removeInfo(*this); else - ShapeOutsideInfo::ensureInfo(*this).dirtyShapeSize(); + ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty(); if (shapeOutside || shapeOutside != oldShapeOutside) markShapeOutsideDependentsForLayout(); } -#endif void RenderBox::updateFromStyle() { RenderBoxModelObject::updateFromStyle(); const RenderStyle& styleToUse = style(); - bool isRootObject = isRoot(); + bool isDocElementRenderer = isDocumentElementRenderer(); bool isViewObject = isRenderView(); // The root and the RenderView always paint their backgrounds/borders. - if (isRootObject || isViewObject) - setHasBoxDecorations(true); + if (isDocElementRenderer || isViewObject) + setHasVisibleBoxDecorations(true); setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating()); // We also handle <body> and <html>, whose overflow applies to the viewport. - if (styleToUse.overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) { + if (styleToUse.overflowX() != OVISIBLE && !isDocElementRenderer && isRenderBlock()) { bool boxHasOverflowClip = true; if (isBody()) { // Overflow on the body can propagate to the viewport under the following conditions. // (1) The root element is <html>. // (2) We are the primary <body> (can be checked by looking at document.body). // (3) The root element has visible overflow. - if (document().documentElement()->hasTagName(htmlTag) + if (is<HTMLHtmlElement>(*document().documentElement()) && document().body() == element() && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) { boxHasOverflowClip = false; } } - // Check for overflow clip. // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value. if (boxHasOverflowClip) { - if (!s_hadOverflowClip) - // Erase the overflow - repaint(); + if (!s_hadOverflowClip && hasRenderOverflow()) { + // Erase the overflow. + // Overflow changes have to result in immediate repaints of the entire layout overflow area because + // repaints issued by removal of descendants get clipped using the updated style when they shouldn't. + repaintRectangle(visualOverflowRect()); + repaintRectangle(layoutOverflowRect()); + } setHasOverflowClip(); } } - - setHasTransform(styleToUse.hasTransformRelatedProperty()); + setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty()); setHasReflection(styleToUse.boxReflect()); } @@ -473,7 +573,7 @@ void RenderBox::layout() LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode()); while (child) { if (child->needsLayout()) - toRenderElement(child)->layout(); + downcast<RenderElement>(*child).layout(); ASSERT(!child->needsLayout()); child = child->nextSibling(); } @@ -494,76 +594,77 @@ LayoutUnit RenderBox::clientHeight() const return height() - borderTop() - borderBottom() - horizontalScrollbarHeight(); } -int RenderBox::pixelSnappedClientWidth() const -{ - return snapSizeToPixel(clientWidth(), x() + clientLeft()); -} - -int RenderBox::pixelSnappedClientHeight() const -{ - return snapSizeToPixel(clientHeight(), y() + clientTop()); -} - -int RenderBox::pixelSnappedOffsetWidth() const -{ - return snapSizeToPixel(offsetWidth(), x() + clientLeft()); -} - -int RenderBox::pixelSnappedOffsetHeight() const -{ - return snapSizeToPixel(offsetHeight(), y() + clientTop()); -} - int RenderBox::scrollWidth() const { - if (hasOverflowClip()) + if (hasOverflowClip() && layer()) return layer()->scrollWidth(); // For objects with visible overflow, this matches IE. // FIXME: Need to work right with writing modes. - if (style().isLeftToRightDirection()) - return snapSizeToPixel(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()), x() + clientLeft()); - return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft()); + if (style().isLeftToRightDirection()) { + // FIXME: This should use snappedIntSize() instead with absolute coordinates. + return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft())); + } + return roundToInt(clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft())); } int RenderBox::scrollHeight() const { - if (hasOverflowClip()) + if (hasOverflowClip() && layer()) return layer()->scrollHeight(); // For objects with visible overflow, this matches IE. // FIXME: Need to work right with writing modes. - return snapSizeToPixel(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()), y() + clientTop()); + // FIXME: This should use snappedIntSize() instead with absolute coordinates. + return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop())); } int RenderBox::scrollLeft() const { - return hasOverflowClip() ? layer()->scrollXOffset() : 0; + return hasOverflowClip() && layer() ? layer()->scrollPosition().x() : 0; } int RenderBox::scrollTop() const { - return hasOverflowClip() ? layer()->scrollYOffset() : 0; + return hasOverflowClip() && layer() ? layer()->scrollPosition().y() : 0; +} + +static void setupWheelEventTestTrigger(RenderLayer& layer) +{ + Page& page = layer.renderer().page(); + if (!page.expectsWheelEventTriggers()) + return; + layer.scrollAnimator().setWheelEventTestTrigger(page.testTrigger()); } void RenderBox::setScrollLeft(int newLeft) { - if (hasOverflowClip()) - layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped); + if (!hasOverflowClip() || !layer()) + return; + setupWheelEventTestTrigger(*layer()); + layer()->scrollToXPosition(newLeft, RenderLayer::ScrollOffsetClamped); } void RenderBox::setScrollTop(int newTop) { - if (hasOverflowClip()) - layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped); + if (!hasOverflowClip() || !layer()) + return; + setupWheelEventTestTrigger(*layer()); + layer()->scrollToYPosition(newTop, RenderLayer::ScrollOffsetClamped); } void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const { - rects.append(pixelSnappedIntRect(accumulatedOffset, size())); + rects.append(snappedIntRect(accumulatedOffset, size())); } void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const { - quads.append(localToAbsoluteQuad(FloatRect(0, 0, width(), height()), 0 /* mode */, wasFixed)); + FloatRect localRect(0, 0, width(), height()); + + RenderFlowThread* flowThread = flowThreadContainingBlock(); + if (flowThread && flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY())) + return; + + quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed)); } void RenderBox::updateLayerTransform() @@ -573,7 +674,7 @@ void RenderBox::updateLayerTransform() layer()->updateTransform(); } -LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const +LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock& cb, RenderRegion* region) const { const RenderStyle& styleToUse = style(); if (!styleToUse.logicalMaxWidth().isUndefined()) @@ -581,31 +682,33 @@ LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWi return std::max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, region)); } -LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight) const +LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, std::optional<LayoutUnit> intrinsicContentHeight) const { const RenderStyle& styleToUse = style(); if (!styleToUse.logicalMaxHeight().isUndefined()) { - LayoutUnit maxH = computeLogicalHeightUsing(styleToUse.logicalMaxHeight()); - if (maxH != -1) - logicalHeight = std::min(logicalHeight, maxH); + if (std::optional<LayoutUnit> maxH = computeLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight)) + logicalHeight = std::min(logicalHeight, maxH.value()); } - return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse.logicalMinHeight())); + if (std::optional<LayoutUnit> computedLogicalHeight = computeLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight)) + return std::max(logicalHeight, computedLogicalHeight.value()); + return logicalHeight; } -LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight) const +LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, std::optional<LayoutUnit> intrinsicContentHeight) const { const RenderStyle& styleToUse = style(); if (!styleToUse.logicalMaxHeight().isUndefined()) { - LayoutUnit maxH = computeContentLogicalHeight(styleToUse.logicalMaxHeight()); - if (maxH != -1) - logicalHeight = std::min(logicalHeight, maxH); + if (std::optional<LayoutUnit> maxH = computeContentLogicalHeight(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight)) + logicalHeight = std::min(logicalHeight, maxH.value()); } - return std::max(logicalHeight, computeContentLogicalHeight(styleToUse.logicalMinHeight())); + if (std::optional<LayoutUnit> computedContentLogicalHeight = computeContentLogicalHeight(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight)) + return std::max(logicalHeight, computedContentLogicalHeight.value()); + return logicalHeight; } RoundedRect::Radii RenderBox::borderRadii() const { - RenderStyle& style = this->style(); + auto& style = this->style(); LayoutRect bounds = frameRect(); unsigned borderLeft = style.borderLeftWidth(); @@ -615,10 +718,19 @@ RoundedRect::Radii RenderBox::borderRadii() const return style.getRoundedBorderFor(bounds).radii(); } +LayoutRect RenderBox::contentBoxRect() const +{ + LayoutUnit x = borderLeft() + paddingLeft(); + if (shouldPlaceBlockDirectionScrollbarOnLeft()) + x += verticalScrollbarWidth(); + LayoutUnit y = borderTop() + paddingTop(); + return LayoutRect(x, y, contentWidth(), contentHeight()); +} + IntRect RenderBox::absoluteContentBox() const { // This is wrong with transforms and flipped writing modes. - IntRect rect = pixelSnappedIntRect(contentBoxRect()); + IntRect rect = snappedIntRect(contentBoxRect()); FloatPoint absPos = localToAbsolute(); rect.move(absPos.x(), absPos.y()); return rect; @@ -642,44 +754,20 @@ LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repa else containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer); - box = containerRelativeQuad.enclosingBoundingBox(); + box = LayoutRect(containerRelativeQuad.boundingBox()); } // FIXME: layoutDelta needs to be applied in parts before/after transforms and // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308 box.move(view().layoutDelta()); - return box; + return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor())); } -void RenderBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*) +void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*) { if (!size().isEmpty()) - rects.append(pixelSnappedIntRect(additionalOffset, size())); -} - -LayoutRect RenderBox::reflectionBox() const -{ - LayoutRect result; - if (!style().boxReflect()) - return result; - LayoutRect box = borderBoxRect(); - result = box; - switch (style().boxReflect()->direction()) { - case ReflectionBelow: - result.move(0, box.height() + reflectionOffset()); - break; - case ReflectionAbove: - result.move(0, -box.height() - reflectionOffset()); - break; - case ReflectionLeft: - result.move(-box.width() - reflectionOffset(), 0); - break; - case ReflectionRight: - result.move(box.width() + reflectionOffset(), 0); - break; - } - return result; + rects.append(LayoutRect(additionalOffset, size())); } int RenderBox::reflectionOffset() const @@ -722,13 +810,13 @@ bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) c bool RenderBox::includeVerticalScrollbarSize() const { - return hasOverflowClip() && !layer()->hasOverlayScrollbars() + return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars() && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO); } bool RenderBox::includeHorizontalScrollbarSize() const { - return hasOverflowClip() && !layer()->hasOverlayScrollbars() + return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars() && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO); } @@ -742,18 +830,18 @@ int RenderBox::horizontalScrollbarHeight() const return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0; } -int RenderBox::instrinsicScrollbarLogicalWidth() const +int RenderBox::intrinsicScrollbarLogicalWidth() const { if (!hasOverflowClip()) return 0; - if (isHorizontalWritingMode() && style().overflowY() == OSCROLL) { - ASSERT(layer()->hasVerticalScrollbar()); + if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) { + ASSERT(layer() && layer()->hasVerticalScrollbar()); return verticalScrollbarWidth(); } - if (!isHorizontalWritingMode() && style().overflowX() == OSCROLL) { - ASSERT(layer()->hasHorizontalScrollbar()); + if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) { + ASSERT(layer() && layer()->hasHorizontalScrollbar()); return horizontalScrollbarHeight(); } @@ -782,9 +870,9 @@ bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, return true; RenderBlock* nextScrollBlock = containingBlock(); - if (nextScrollBlock && nextScrollBlock->isRenderNamedFlowThread()) { + if (is<RenderNamedFlowThread>(nextScrollBlock)) { ASSERT(startBox); - nextScrollBlock = toRenderFlowThread(nextScrollBlock)->regionFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox); + nextScrollBlock = downcast<RenderNamedFlowThread>(*nextScrollBlock).fragmentFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox); } if (nextScrollBlock && !nextScrollBlock->isRenderView()) @@ -799,7 +887,7 @@ bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularit RenderLayer* l = layer(); if (l) { -#if PLATFORM(MAC) +#if PLATFORM(COCOA) // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End). if (granularity == ScrollByDocument) scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier); @@ -825,9 +913,15 @@ bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularit bool RenderBox::canBeScrolledAndHasScrollableArea() const { - return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth()); + return canBeProgramaticallyScrolled() && (hasHorizontalOverflow() || hasVerticalOverflow()); } - + +bool RenderBox::isScrollableOrRubberbandableBox() const +{ + return canBeScrolledAndHasScrollableArea(); +} + +// FIXME: This is badly named. overflow:hidden can be programmatically scrolled, yet this returns false in that case. bool RenderBox::canBeProgramaticallyScrolled() const { if (isRenderView()) @@ -836,8 +930,7 @@ bool RenderBox::canBeProgramaticallyScrolled() const if (!hasOverflowClip()) return false; - bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY(); - if (scrollsOverflow() && hasScrollableOverflow) + if (hasScrollableOverflowX() || hasScrollableOverflowY()) return true; return element() && element()->hasEditableStyle(); @@ -872,7 +965,7 @@ bool RenderBox::canAutoscroll() const IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const { IntRect box(absoluteBoundingBoxRect()); - box.move(view().frameView().scrollOffset()); + box.moveBy(view().frameView().scrollPosition()); IntRect windowBox = view().frameView().contentsToWindow(box); IntPoint windowAutoscrollPoint = windowPoint; @@ -892,14 +985,14 @@ IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) con RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer) { - while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) { - if (renderer->isRenderView() && renderer->document().ownerElement()) + while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) { + if (is<RenderView>(*renderer) && renderer->document().ownerElement()) renderer = renderer->document().ownerElement()->renderer(); else renderer = renderer->parent(); } - return renderer && renderer->isBox() ? toRenderBox(renderer) : 0; + return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr; } void RenderBox::panScroll(const IntPoint& source) @@ -908,16 +1001,30 @@ void RenderBox::panScroll(const IntPoint& source) layer()->panScrollFromPoint(source); } +bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const +{ + bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars(); + return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto); +} + +bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const +{ + bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars(); + return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto); +} + bool RenderBox::needsPreferredWidthsRecalculation() const { - return style().paddingStart().isPercent() || style().paddingEnd().isPercent(); + return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated(); } -IntSize RenderBox::scrolledContentOffset() const +ScrollPosition RenderBox::scrollPosition() const { - ASSERT(hasOverflowClip()); + if (!hasOverflowClip()) + return { 0, 0 }; + ASSERT(hasLayer()); - return layer()->scrolledContentOffset(); + return layer()->scrollPosition(); } LayoutSize RenderBox::cachedSizeForOverflowClip() const @@ -927,10 +1034,10 @@ LayoutSize RenderBox::cachedSizeForOverflowClip() const return layer()->size(); } -void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const +void RenderBox::applyCachedClipAndScrollPositionForRepaint(LayoutRect& paintRect) const { flipForWritingMode(paintRect); - paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden. + paintRect.moveBy(-scrollPosition()); // For overflow:auto/scroll/hidden. // Do not clip scroll layer contents to reduce the number of repaints while scrolling. if (usesCompositedScrolling()) { @@ -976,12 +1083,12 @@ LayoutUnit RenderBox::maxPreferredLogicalWidth() const return m_maxPreferredLogicalWidth; } -bool RenderBox::hasOverrideHeight() const +bool RenderBox::hasOverrideLogicalContentHeight() const { return gOverrideHeightMap && gOverrideHeightMap->contains(this); } -bool RenderBox::hasOverrideWidth() const +bool RenderBox::hasOverrideLogicalContentWidth() const { return gOverrideWidthMap && gOverrideWidthMap->contains(this); } @@ -1020,23 +1127,23 @@ void RenderBox::clearOverrideSize() LayoutUnit RenderBox::overrideLogicalContentWidth() const { - ASSERT(hasOverrideWidth()); + ASSERT(hasOverrideLogicalContentWidth()); return gOverrideWidthMap->get(this); } LayoutUnit RenderBox::overrideLogicalContentHeight() const { - ASSERT(hasOverrideHeight()); + ASSERT(hasOverrideLogicalContentHeight()); return gOverrideHeightMap->get(this); } -LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const +std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalWidth() const { ASSERT(hasOverrideContainingBlockLogicalWidth()); return gOverrideContainingBlockLogicalWidthMap->get(this); } -LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const +std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalHeight() const { ASSERT(hasOverrideContainingBlockLogicalHeight()); return gOverrideContainingBlockLogicalHeightMap->get(this); @@ -1052,17 +1159,17 @@ bool RenderBox::hasOverrideContainingBlockLogicalHeight() const return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this); } -void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth) +void RenderBox::setOverrideContainingBlockContentLogicalWidth(std::optional<LayoutUnit> logicalWidth) { if (!gOverrideContainingBlockLogicalWidthMap) - gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap; + gOverrideContainingBlockLogicalWidthMap = new OverrideOptionalSizeMap; gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth); } -void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight) +void RenderBox::setOverrideContainingBlockContentLogicalHeight(std::optional<LayoutUnit> logicalHeight) { if (!gOverrideContainingBlockLogicalHeightMap) - gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap; + gOverrideContainingBlockLogicalHeightMap = new OverrideOptionalSizeMap; gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight); } @@ -1079,6 +1186,38 @@ void RenderBox::clearOverrideContainingBlockContentLogicalHeight() gOverrideContainingBlockLogicalHeightMap->remove(this); } +LayoutUnit RenderBox::extraInlineOffset() const +{ + return gExtraInlineOffsetMap ? gExtraInlineOffsetMap->get(this) : LayoutUnit(); +} + +LayoutUnit RenderBox::extraBlockOffset() const +{ + return gExtraBlockOffsetMap ? gExtraBlockOffsetMap->get(this) : LayoutUnit(); +} + +void RenderBox::setExtraInlineOffset(LayoutUnit inlineOffest) +{ + if (!gExtraInlineOffsetMap) + gExtraInlineOffsetMap = new OverrideSizeMap; + gExtraInlineOffsetMap->set(this, inlineOffest); +} + +void RenderBox::setExtraBlockOffset(LayoutUnit blockOffest) +{ + if (!gExtraBlockOffsetMap) + gExtraBlockOffsetMap = new OverrideSizeMap; + gExtraBlockOffsetMap->set(this, blockOffest); +} + +void RenderBox::clearExtraInlineAndBlockOffests() +{ + if (gExtraInlineOffsetMap) + gExtraInlineOffsetMap->remove(this); + if (gExtraBlockOffsetMap) + gExtraBlockOffsetMap->remove(this); +} + LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const { LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth(); @@ -1102,11 +1241,14 @@ LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) return std::max<LayoutUnit>(0, width); } -LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const +LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit> height) const { + if (!height) + return 0; + LayoutUnit result = height.value(); if (style().boxSizing() == BORDER_BOX) - height -= borderAndPaddingLogicalHeight(); - return std::max<LayoutUnit>(0, height); + result -= borderAndPaddingLogicalHeight(); + return std::max(LayoutUnit(), result); } // Hit Testing @@ -1122,9 +1264,16 @@ bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result } } + RenderFlowThread* flowThread = flowThreadContainingBlock(); + RenderRegion* regionToUse = flowThread ? downcast<RenderNamedFlowFragment>(flowThread->currentRegion()) : nullptr; + + // If the box is not contained by this region there's no point in going further. + if (regionToUse && !flowThread->objectShouldFragmentInFlowRegion(this, regionToUse)) + return false; + // Check our bounds next. For this purpose always assume that we can only be hit in the // foreground phase (which is true for replaced elements like images). - LayoutRect boundsRect = borderBoxRectInRegion(locationInContainer.region()); + LayoutRect boundsRect = borderBoxRectInRegion(regionToUse); boundsRect.moveBy(adjustedLocation); if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) { updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation)); @@ -1139,20 +1288,22 @@ bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo) { + ASSERT(isDocumentElementRenderer()); if (paintInfo.skipRootBackground()) return; - auto& rootBackgroundRenderer = rendererForRootBackground(); - - const FillLayer* bgLayer = rootBackgroundRenderer.style().backgroundLayers(); - Color bgColor = rootBackgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor); + auto* rootBackgroundRenderer = view().rendererForRootBackground(); + if (!rootBackgroundRenderer) + return; - paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, &rootBackgroundRenderer); + auto& style = rootBackgroundRenderer->style(); + auto color = style.visitedDependentColor(CSSPropertyBackgroundColor); + paintFillLayers(paintInfo, color, style.backgroundLayers(), view().backgroundRect(), BackgroundBleedNone, CompositeSourceOver, rootBackgroundRenderer); } -BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const +BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext& context) const { - if (context->paintingDisabled()) + if (context.paintingDisabled()) return BackgroundBleedNone; const RenderStyle& style = this->style(); @@ -1160,7 +1311,7 @@ BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsCo if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered()) return BackgroundBleedNone; - AffineTransform ctm = context->getCTM(); + AffineTransform ctm = context.getCTM(); FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale())); // Because RoundedRect uses IntRect internally the inset applied by the @@ -1190,7 +1341,7 @@ void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& pai if (!paintInfo.shouldPaintWithinRoot(*this)) return; - LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion); + LayoutRect paintRect = borderBoxRectInRegion(currentRenderNamedFlowFragment()); paintRect.moveBy(paintOffset); #if PLATFORM(IOS) @@ -1201,89 +1352,111 @@ void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& pai paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop } #endif - BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context); + BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context()); // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have // custom shadows of their own. - if (!boxShadowShouldBeAppliedToBackground(bleedAvoidance)) - paintBoxShadow(paintInfo, paintRect, &style(), Normal); + if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance)) + paintBoxShadow(paintInfo, paintRect, style(), Normal); - GraphicsContextStateSaver stateSaver(*paintInfo.context, false); + GraphicsContextStateSaver stateSaver(paintInfo.context(), false); if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) { // To avoid the background color bleeding out behind the border, we'll render background and border // into a transparency layer, and then clip that in one go (which requires setting up the clip before // beginning the layer). - RoundedRect border = style().getRoundedBorderFor(paintRect, &view()); stateSaver.save(); - paintInfo.context->clipRoundedRect(border); - paintInfo.context->beginTransparencyLayer(1); + paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor())); + paintInfo.context().beginTransparencyLayer(1); } // If we have a native theme appearance, paint that before painting our background. // The theme will tell us whether or not we should also paint the CSS background. - IntRect snappedPaintRect(pixelSnappedIntRect(paintRect)); - bool themePainted = style().hasAppearance() && !theme().paint(this, paintInfo, snappedPaintRect); - if (!themePainted) { + bool borderOrBackgroundPaintingIsNeeded = true; + if (style().hasAppearance()) { + ControlStates* controlStates = controlStatesForRenderer(*this); + borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect); + if (controlStates->needsRepaint()) + view().scheduleLazyRepaint(*this); + } + + if (borderOrBackgroundPaintingIsNeeded) { if (bleedAvoidance == BackgroundBleedBackgroundOverBorder) - paintBorder(paintInfo, paintRect, &style(), bleedAvoidance); + paintBorder(paintInfo, paintRect, style(), bleedAvoidance); paintBackground(paintInfo, paintRect, bleedAvoidance); if (style().hasAppearance()) - theme().paintDecorations(this, paintInfo, snappedPaintRect); + theme().paintDecorations(*this, paintInfo, paintRect); } - paintBoxShadow(paintInfo, paintRect, &style(), Inset); + paintBoxShadow(paintInfo, paintRect, style(), Inset); // The theme will tell us whether or not we should also paint the CSS border. - if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (!themePainted && theme().paintBorderOnly(this, paintInfo, snappedPaintRect))) && style().hasBorder()) - paintBorder(paintInfo, paintRect, &style(), bleedAvoidance); + if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasVisibleBorderDecoration()) + paintBorder(paintInfo, paintRect, style(), bleedAvoidance); if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) - paintInfo.context->endTransparencyLayer(); + paintInfo.context().endTransparencyLayer(); +} + +bool RenderBox::paintsOwnBackground() const +{ + if (isBody()) { + // The <body> only paints its background if the root element has defined a background independent of the body, + // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject). + auto documentElementRenderer = document().documentElement()->renderer(); + return !documentElementRenderer + || documentElementRenderer->hasBackground() + || (documentElementRenderer != parent()); + } + + return true; } void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance) { - if (isRoot()) { + if (isDocumentElementRenderer()) { paintRootBoxFillLayers(paintInfo); return; } - if (isBody() && skipBodyBackground(this)) + + if (!paintsOwnBackground()) return; - if (backgroundIsKnownToBeObscured() && !boxShadowShouldBeAppliedToBackground(bleedAvoidance)) + + if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance)) return; + paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance); } -bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent) const +bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const { ASSERT(hasBackground()); - LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect()); + LayoutRect backgroundRect = snappedIntRect(borderBoxRect()); Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor); - if (backgroundColor.isValid() && backgroundColor.alpha()) { + if (backgroundColor.isVisible()) { paintedExtent = backgroundRect; return true; } - if (!style().backgroundLayers()->image() || style().backgroundLayers()->next()) { + auto& layers = style().backgroundLayers(); + if (!layers.image() || layers.next()) { paintedExtent = backgroundRect; return true; } - BackgroundImageGeometry geometry; - calculateBackgroundImageGeometry(0, style().backgroundLayers(), backgroundRect, geometry); + auto geometry = calculateBackgroundImageGeometry(nullptr, layers, paintOffset, backgroundRect); paintedExtent = geometry.destRect(); return !geometry.hasNonLocalGeometry(); } bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const { - if (isBody() && skipBodyBackground(this)) + if (!paintsOwnBackground()) return false; Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor); - if (!backgroundColor.isValid() || backgroundColor.hasAlpha()) + if (!backgroundColor.isOpaque()) return false; // If the element has appearance, it might be painted by theme. @@ -1294,11 +1467,15 @@ bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) c return false; // FIXME: Check the opaqueness of background images. + if (hasClip() || hasClipPath()) + return false; + // FIXME: Use rounded rect if border radius is present. if (style().hasBorderRadius()) return false; + // FIXME: The background color clip is defined by the last layer. - if (style().backgroundLayers()->next()) + if (style().backgroundLayers().next()) return false; LayoutRect backgroundRect; switch (style().backgroundClip()) { @@ -1324,22 +1501,20 @@ static bool isCandidateForOpaquenessTest(const RenderBox& childBox) return false; if (childStyle.visibility() != VISIBLE) return false; -#if ENABLE(CSS_SHAPES) if (childStyle.shapeOutside()) return false; -#endif if (!childBox.width() || !childBox.height()) return false; if (RenderLayer* childLayer = childBox.layer()) { -#if USE(ACCELERATED_COMPOSITING) if (childLayer->isComposited()) return false; -#endif // FIXME: Deal with z-index. if (!childStyle.hasAutoZIndex()) return false; if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter()) return false; + if (!childBox.scrollPosition().isZero()) + return false; } return true; } @@ -1372,39 +1547,39 @@ bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, u return false; } -bool RenderBox::computeBackgroundIsKnownToBeObscured() +bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset) { // Test to see if the children trivially obscure the background. // FIXME: This test can be much more comprehensive. if (!hasBackground()) return false; // Table and root background painting is special. - if (isTable() || isRoot()) + if (isTable() || isDocumentElementRenderer()) return false; LayoutRect backgroundRect; - if (!getBackgroundPaintedExtent(backgroundRect)) + if (!getBackgroundPaintedExtent(paintOffset, backgroundRect)) return false; return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth); } bool RenderBox::backgroundHasOpaqueTopLayer() const { - const FillLayer* fillLayer = style().backgroundLayers(); - if (!fillLayer || fillLayer->clip() != BorderFillBox) + auto& fillLayer = style().backgroundLayers(); + if (fillLayer.clip() != BorderFillBox) return false; // Clipped with local scrolling - if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment) + if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment) return false; - if (fillLayer->hasOpaqueImage(this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style().effectiveZoom())) + if (fillLayer.hasOpaqueImage(*this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(this, style().effectiveZoom())) return true; - // If there is only one layer and no image, check whether the background color is opaque - if (!fillLayer->next() && !fillLayer->hasImage()) { + // If there is only one layer and no image, check whether the background color is opaque. + if (!fillLayer.next() && !fillLayer.hasImage()) { Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor); - if (bgColor.isValid() && bgColor.alpha() == 255) + if (bgColor.isOpaque()) return true; } @@ -1413,13 +1588,22 @@ bool RenderBox::backgroundHasOpaqueTopLayer() const void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset) { - if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled()) + if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context().paintingDisabled()) return; LayoutRect paintRect = LayoutRect(paintOffset, size()); paintMaskImages(paintInfo, paintRect); } +void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset) +{ + if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context().paintingDisabled()) + return; + + LayoutRect paintRect = LayoutRect(paintOffset, size()); + paintInfo.context().fillRect(snappedIntRect(paintRect), Color::black); +} + void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect) { // Figure out if we need to push a transparency layer to render our mask. @@ -1432,31 +1616,28 @@ void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& pa if (!compositedMask || flattenCompositingLayers) { pushTransparencyLayer = true; - StyleImage* maskBoxImage = style().maskBoxImage().image(); - const FillLayer* maskLayers = style().maskLayers(); // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content. - if (maskBoxImage) + if (auto* maskBoxImage = style().maskBoxImage().image()) allMaskImagesLoaded &= maskBoxImage->isLoaded(); - if (maskLayers) - allMaskImagesLoaded &= maskLayers->imagesAreLoaded(); + allMaskImagesLoaded &= style().maskLayers().imagesAreLoaded(); - paintInfo.context->setCompositeOperation(CompositeDestinationIn); - paintInfo.context->beginTransparencyLayer(1); + paintInfo.context().setCompositeOperation(CompositeDestinationIn); + paintInfo.context().beginTransparencyLayer(1); compositeOp = CompositeSourceOver; } if (allMaskImagesLoaded) { paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp); - paintNinePieceImage(paintInfo.context, paintRect, &style(), style().maskBoxImage(), compositeOp); + paintNinePieceImage(paintInfo.context(), paintRect, style(), style().maskBoxImage(), compositeOp); } if (pushTransparencyLayer) - paintInfo.context->endTransparencyLayer(); + paintInfo.context().endTransparencyLayer(); } -LayoutRect RenderBox::maskClipRect() +LayoutRect RenderBox::maskClipRect(const LayoutPoint& paintOffset) { const NinePieceImage& maskBoxImage = style().maskBoxImage(); if (maskBoxImage.image()) { @@ -1469,73 +1650,71 @@ LayoutRect RenderBox::maskClipRect() LayoutRect result; LayoutRect borderBox = borderBoxRect(); - for (const FillLayer* maskLayer = style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) { + for (auto* maskLayer = &style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) { if (maskLayer->image()) { - BackgroundImageGeometry geometry; // Masks should never have fixed attachment, so it's OK for paintContainer to be null. - calculateBackgroundImageGeometry(0, maskLayer, borderBox, geometry); - result.unite(geometry.destRect()); + result.unite(calculateBackgroundImageGeometry(nullptr, *maskLayer, paintOffset, borderBox).destRect()); } } return result; } -void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect, +void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& color, const FillLayer& fillLayer, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject) { Vector<const FillLayer*, 8> layers; - const FillLayer* curLayer = fillLayer; bool shouldDrawBackgroundInSeparateBuffer = false; - while (curLayer) { - layers.append(curLayer); + + for (auto* layer = &fillLayer; layer; layer = layer->next()) { + layers.append(layer); + + if (layer->blendMode() != BlendModeNormal) + shouldDrawBackgroundInSeparateBuffer = true; + // Stop traversal when an opaque layer is encountered. - // FIXME : It would be possible for the following occlusion culling test to be more aggressive + // FIXME: It would be possible for the following occlusion culling test to be more aggressive // on layers with no repeat by testing whether the image covers the layout rect. // Testing that here would imply duplicating a lot of calculations that are currently done in // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here // and pass it down. - if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal) - shouldDrawBackgroundInSeparateBuffer = true; - // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting. - if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(this) && curLayer->image()->canRender(this, style().effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal) + if (layer->clipOccludesNextLayers(layer == &fillLayer) && layer->hasOpaqueImage(*this) && layer->image()->canRender(this, style().effectiveZoom()) && layer->hasRepeatXY() && layer->blendMode() == BlendModeNormal) break; - curLayer = curLayer->next(); } - GraphicsContext* context = paintInfo.context; - if (!context) - shouldDrawBackgroundInSeparateBuffer = false; - if (shouldDrawBackgroundInSeparateBuffer) - context->beginTransparencyLayer(1); + auto& context = paintInfo.context(); + auto baseBgColorUsage = BaseBackgroundColorUse; - Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend(); - for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it) - paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject); + if (shouldDrawBackgroundInSeparateBuffer) { + paintFillLayer(paintInfo, color, *layers.last(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly); + baseBgColorUsage = BaseBackgroundColorSkip; + context.beginTransparencyLayer(1); + } + + auto topLayer = layers.rend(); + for (auto it = layers.rbegin(); it != topLayer; ++it) + paintFillLayer(paintInfo, color, **it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage); if (shouldDrawBackgroundInSeparateBuffer) - context->endTransparencyLayer(); + context.endTransparencyLayer(); } -void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect, - BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject) +void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer& fillLayer, const LayoutRect& rect, + BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage) { - paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, LayoutSize(), op, backgroundObject); + paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage); } -#if USE(ACCELERATED_COMPOSITING) -static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers) +static bool layersUseImage(WrappedImagePtr image, const FillLayer& layers) { - for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) { - if (curLayer->image() && image == curLayer->image()->data()) + for (auto* layer = &layers; layer; layer = layer->next()) { + if (layer->image() && image == layer->image()->data()) return true; } - return false; } -#endif void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*) { @@ -1548,12 +1727,16 @@ void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*) return; } + ShapeValue* shapeOutsideValue = style().shapeOutside(); + if (!view().frameView().isInRenderTreeLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) { + ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty(); + markShapeOutsideDependentsForLayout(); + } + bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true); if (!didFullRepaint) repaintLayerRectsForImage(image, style().maskLayers(), false); - -#if USE(ACCELERATED_COMPOSITING) if (!isComposited()) return; @@ -1561,37 +1744,35 @@ void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*) layer()->contentChanged(MaskImageChanged); if (layersUseImage(image, style().backgroundLayers())) layer()->contentChanged(BackgroundImageChanged); -#endif } -bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground) +bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground) { LayoutRect rendererRect; - RenderBox* layerRenderer = 0; + RenderBox* layerRenderer = nullptr; - for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) { - if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) { + for (auto* layer = &layers; layer; layer = layer->next()) { + if (layer->image() && image == layer->image()->data() && layer->image()->canRender(this, style().effectiveZoom())) { // Now that we know this image is being used, compute the renderer and the rect if we haven't already. - bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground())); + bool drawingRootBackground = drawingBackground && (isDocumentElementRenderer() || (isBody() && !document().documentElement()->renderer()->hasBackground())); if (!layerRenderer) { if (drawingRootBackground) { layerRenderer = &view(); - LayoutUnit rw = toRenderView(*layerRenderer).frameView().contentsWidth(); - LayoutUnit rh = toRenderView(*layerRenderer).frameView().contentsHeight(); + LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth(); + LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight(); rendererRect = LayoutRect(-layerRenderer->marginLeft(), -layerRenderer->marginTop(), - std::max(layerRenderer->width() + layerRenderer->marginWidth() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw), - std::max(layerRenderer->height() + layerRenderer->marginHeight() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh)); + std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw), + std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh)); } else { layerRenderer = this; rendererRect = borderBoxRect(); } } - - BackgroundImageGeometry geometry; - layerRenderer->calculateBackgroundImageGeometry(0, curLayer, rendererRect, geometry); + // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping) + BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *layer, LayoutPoint(), rendererRect); if (geometry.hasNonLocalGeometry()) { // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds // in order to get the right destRect, just repaint the entire renderer. @@ -1599,15 +1780,15 @@ bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer return true; } - IntRect rectToRepaint = geometry.destRect(); + LayoutRect rectToRepaint = geometry.destRect(); bool shouldClipToLayer = true; // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an // extendedBackground. We should only extend the rect if it is already extending the full width or height // of the rendererRect. - if (drawingRootBackground && view().frameView().hasExtendedBackground()) { + if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) { shouldClipToLayer = false; - IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRect(); + IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting(); if (rectToRepaint.width() == rendererRect.width()) { rectToRepaint.move(extendedBackgroundRect.x(), 0); rectToRepaint.setWidth(extendedBackgroundRect.width()); @@ -1618,7 +1799,7 @@ bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer } } - layerRenderer->repaintRectangle(rectToRepaint, false, shouldClipToLayer); + layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer); if (geometry.destRect() == rendererRect) return true; } @@ -1626,28 +1807,6 @@ bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer return false; } -#if PLATFORM(MAC) - -void RenderBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type, bool behindText) -{ - Page* page = frame().page(); - if (!page) - return; - - InlineBox* boxWrap = inlineBoxWrapper(); - RootInlineBox* r = boxWrap ? &boxWrap->root() : 0; - if (r) { - FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + r->selectionTop(), r->logicalWidth(), r->selectionHeight()); - FloatRect imageRect(paintOffset.x() + x(), rootRect.y(), width(), rootRect.height()); - page->chrome().client().paintCustomHighlight(element(), type, imageRect, rootRect, behindText, false); - } else { - FloatRect imageRect(paintOffset.x() + x(), paintOffset.y() + y(), width(), height()); - page->chrome().client().paintCustomHighlight(element(), type, imageRect, imageRect, behindText, false); - } -} - -#endif - bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset) { if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask) @@ -1666,11 +1825,12 @@ bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumu paintObject(paintInfo, accumulatedOffset); paintInfo.phase = PaintPhaseChildBlockBackgrounds; } - IntRect clipRect = pixelSnappedIntRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion, IgnoreOverlayScrollbarSize, paintInfo.phase)); - paintInfo.context->save(); + float deviceScaleFactor = document().deviceScaleFactor(); + FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor); + paintInfo.context().save(); if (style().hasBorderRadius()) - paintInfo.context->clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size()))); - paintInfo.context->clip(clipRect); + paintInfo.context().clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor)); + paintInfo.context().clip(clipRect); return true; } @@ -1678,7 +1838,7 @@ void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, { ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer())); - paintInfo.context->restore(); + paintInfo.context().restore(); if (originalPhase == PaintPhaseOutline) { paintInfo.phase = PaintPhaseSelfOutline; paintObject(paintInfo, accumulatedOffset); @@ -1696,11 +1856,11 @@ LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom())); // Subtract out scrollbars if we have them. - if (layer()) { - if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) + if (layer()) { + if (shouldPlaceBlockDirectionScrollbarOnLeft()) clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0); clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy)); - } + } return clipRect; } @@ -1734,17 +1894,18 @@ LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region return clipRect; } -LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const +LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock& cb, RenderRegion* region) const { - RenderRegion* containingBlockRegion = 0; + RenderRegion* containingBlockRegion = nullptr; LayoutUnit logicalTopPosition = logicalTop(); if (region) { LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit(); logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion); - containingBlockRegion = cb->clampToStartAndEndRegions(region); + containingBlockRegion = cb.clampToStartAndEndRegions(region); } - LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd; + LayoutUnit logicalHeight = cb.logicalHeightForChild(*this); + LayoutUnit result = cb.availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd; // We need to see if margins on either the start side or the end side can contain the floats in question. If they can, // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line @@ -1752,9 +1913,9 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar // 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 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them. if (childMarginStart > 0) { - LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion); + LayoutUnit startContentSide = cb.startOffsetForContent(containingBlockRegion); LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart; - LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion); + LayoutUnit startOffset = cb.startOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight); if (startOffset > startContentSideWithMargin) result += childMarginStart; else @@ -1762,9 +1923,9 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar } if (childMarginEnd > 0) { - LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion); + LayoutUnit endContentSide = cb.endOffsetForContent(containingBlockRegion); LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd; - LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion); + LayoutUnit endOffset = cb.endOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight); if (endOffset > endContentSideWithMargin) result += childMarginEnd; else @@ -1776,24 +1937,26 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const { - if (hasOverrideContainingBlockLogicalWidth()) - return overrideContainingBlockContentLogicalWidth(); + if (hasOverrideContainingBlockLogicalWidth()) { + if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth()) + return overrideLogicalWidth.value(); + } - RenderBlock* cb = containingBlock(); - if (!cb) - return LayoutUnit(); - return cb->availableLogicalWidth(); + if (RenderBlock* cb = containingBlock()) + return cb->availableLogicalWidth(); + return LayoutUnit(); } LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const { - if (hasOverrideContainingBlockLogicalHeight()) - return overrideContainingBlockContentLogicalHeight(); + if (hasOverrideContainingBlockLogicalHeight()) { + if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight()) + return overrideLogicalHeight.value(); + } - RenderBlock* cb = containingBlock(); - if (!cb) - return LayoutUnit(); - return cb->availableLogicalHeight(heightType); + if (RenderBlock* cb = containingBlock()) + return cb->availableLogicalHeight(heightType); + return LayoutUnit(); } LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const @@ -1815,23 +1978,25 @@ LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const { RenderBlock* cb = containingBlock(); - RenderRegion* containingBlockRegion = 0; + RenderRegion* containingBlockRegion = nullptr; LayoutUnit logicalTopPosition = logicalTop(); if (region) { LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit(); logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion); containingBlockRegion = cb->clampToStartAndEndRegions(region); } - return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding)); + return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding)); } LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const { - if (hasOverrideContainingBlockLogicalHeight()) - return overrideContainingBlockContentLogicalHeight(); + if (hasOverrideContainingBlockLogicalHeight()) { + if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight()) + return overrideLogicalHeight.value(); + } RenderBlock* cb = containingBlock(); - if (cb->hasOverrideHeight()) + if (cb->hasOverrideLogicalContentHeight()) return cb->overrideLogicalContentHeight(); const RenderStyle& containingBlockStyle = cb->style(); @@ -1841,11 +2006,13 @@ LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const if (!logicalHeightLength.isFixed()) { LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth(); LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding); + view().addPercentHeightDescendant(const_cast<RenderBox&>(*this)); + // 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. return std::min(fillAvailableExtent, fillFallbackExtent); } // Use the content box logical height as specified by the style. - return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value()); + return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value())); } void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const @@ -1863,15 +2030,14 @@ void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContain } bool containerSkipped; - auto o = container(repaintContainer, &containerSkipped); - if (!o) + RenderElement* container = this->container(repaintContainer, containerSkipped); + if (!container) return; bool isFixedPos = style().position() == FixedPosition; - bool hasTransform = hasLayer() && layer()->transform(); // If this box has a transform, it acts as a fixed position container for fixed descendants, // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position. - if (hasTransform && !isFixedPos) + if (hasTransform() && !isFixedPos) mode &= ~IsFixed; else if (isFixedPos) mode |= IsFixed; @@ -1879,12 +2045,12 @@ void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContain if (wasFixed) *wasFixed = mode & IsFixed; - LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint())); + LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint())); - bool preserve3D = mode & UseTransforms && (o->style().preserves3D() || style().preserves3D()); - if (mode & UseTransforms && shouldUseTransformFromContainer(o)) { + bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D()); + if (mode & UseTransforms && shouldUseTransformFromContainer(container)) { TransformationMatrix t; - getTransformFromContainer(o, containerOffset, t); + getTransformFromContainer(container, containerOffset, t); transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform); } else transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform); @@ -1892,7 +2058,7 @@ void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContain if (containerSkipped) { // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe // to just subtract the delta between the repaintContainer and o. - LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o); + LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container); transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform); return; } @@ -1901,10 +2067,10 @@ void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContain // For fixed positioned elements inside out-of-flow named flows, we do not want to // map their position further to regions based on their coordinates inside the named flows. - if (!o->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock()) - o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed); + if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock()) + container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed); else - o->mapLocalToContainer(toRenderLayerModelObject(o), transformState, mode, wasFixed); + container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed); } const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const @@ -1912,33 +2078,31 @@ const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObje ASSERT(ancestorToStopAt != this); bool ancestorSkipped; - auto container = this->container(ancestorToStopAt, &ancestorSkipped); + RenderElement* container = this->container(ancestorToStopAt, ancestorSkipped); if (!container) - return 0; + return nullptr; bool isFixedPos = style().position() == FixedPosition; - bool hasTransform = hasLayer() && layer()->transform(); - LayoutSize adjustmentForSkippedAncestor; if (ancestorSkipped) { - // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe - // to just subtract the delta between the ancestor and o. - adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(container); + // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe + // to just subtract the delta between the ancestor and container. + adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container); } bool offsetDependsOnPoint = false; - LayoutSize containerOffset = offsetFromContainer(container, LayoutPoint(), &offsetDependsOnPoint); + LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint); bool preserve3D = container->style().preserves3D() || style().preserves3D(); - if (shouldUseTransformFromContainer(container)) { + if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) { TransformationMatrix t; getTransformFromContainer(container, containerOffset, t); t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height()); - geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform); + geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform()); } else { containerOffset += adjustmentForSkippedAncestor; - geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform); + geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform()); } return ancestorSkipped ? ancestorToStopAt : container; @@ -1947,8 +2111,7 @@ const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObje void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const { bool isFixedPos = style().position() == FixedPosition; - bool hasTransform = hasLayer() && layer()->transform(); - if (hasTransform && !isFixedPos) { + if (hasTransform() && !isFixedPos) { // If this box has a transform, it acts as a fixed position container for fixed descendants, // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position. mode &= ~IsFixed; @@ -1958,40 +2121,26 @@ void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState); } -LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const +LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const { // A region "has" boxes inside it without being their container. - ASSERT(o == container() || o->isRenderRegion()); + ASSERT(&renderer == container() || is<RenderRegion>(renderer)); LayoutSize offset; if (isInFlowPositioned()) offset += offsetForInFlowPosition(); - if (!isInline() || isReplaced()) { - if (!style().hasOutOfFlowPosition() && o->hasColumns()) { - RenderBlock* block = toRenderBlock(o); - LayoutRect columnRect(frameRect()); - block->adjustStartEdgeForWritingModeIncludingColumns(columnRect); - offset += toSize(columnRect.location()); - LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset); - offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset))); - o->adjustForColumns(offset, columnPoint); - offset = block->flipForWritingMode(offset); - - if (offsetDependsOnPoint) - *offsetDependsOnPoint = true; - } else - offset += topLeftLocationOffset(); - } + if (!isInline() || isReplaced()) + offset += topLeftLocationOffset(); - if (o->hasOverflowClip()) - offset -= toRenderBox(o)->scrolledContentOffset(); + if (is<RenderBox>(renderer)) + offset -= toLayoutSize(downcast<RenderBox>(renderer).scrollPosition()); - if (style().position() == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline()) - offset += toRenderInline(o)->offsetForInFlowPositionedInline(this); + if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer)) + offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this); if (offsetDependsOnPoint) - *offsetDependsOnPoint |= o->isRenderFlowThread(); + *offsetDependsOnPoint |= is<RenderFlowThread>(renderer); return offset; } @@ -2003,13 +2152,14 @@ std::unique_ptr<InlineElementBox> RenderBox::createInlineBox() void RenderBox::dirtyLineBoxes(bool fullLayout) { - if (m_inlineBoxWrapper) { - if (fullLayout) { - delete m_inlineBoxWrapper; - m_inlineBoxWrapper = nullptr; - } else - m_inlineBoxWrapper->dirtyLineBoxes(); - } + if (!m_inlineBoxWrapper) + return; + + if (fullLayout) { + delete m_inlineBoxWrapper; + m_inlineBoxWrapper = nullptr; + } else + m_inlineBoxWrapper->dirtyLineBoxes(); } void RenderBox::positionLineBox(InlineElementBox& box) @@ -2022,9 +2172,9 @@ void RenderBox::positionLineBox(InlineElementBox& box) // our object was inline originally, since otherwise it would have ended up underneath // the inlines. RootInlineBox& rootBox = box.root(); - rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), roundedLayoutUnit(box.logicalLeft())); + rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft())); if (style().hasStaticInlinePosition(box.isHorizontal())) - setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly. + setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly. } else { // Our object was a block originally, so we make our normal flow position be // just below the line box (as though all the inlines that came before us got @@ -2032,56 +2182,53 @@ void RenderBox::positionLineBox(InlineElementBox& box) // in flow). This value was cached in the y() of the box. layer()->setStaticBlockPosition(box.logicalTop()); if (style().hasStaticBlockPosition(box.isHorizontal())) - setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly. + setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly. } - - // Nuke the box. - box.removeFromParent(); - delete &box; return; } if (isReplaced()) { - setLocation(roundedLayoutPoint(box.topLeft())); - // m_inlineBoxWrapper should already be 0. Deleting it is a safeguard against security issues. - ASSERT(!m_inlineBoxWrapper); - if (m_inlineBoxWrapper) - deleteLineBoxWrapper(); - m_inlineBoxWrapper = &box; + setLocation(LayoutPoint(box.topLeft())); + setInlineBoxWrapper(&box); } } void RenderBox::deleteLineBoxWrapper() { - if (m_inlineBoxWrapper) { - if (!documentBeingDestroyed()) - m_inlineBoxWrapper->removeFromParent(); - delete m_inlineBoxWrapper; - m_inlineBoxWrapper = nullptr; - } + if (!m_inlineBoxWrapper) + return; + + if (!renderTreeBeingDestroyed()) + m_inlineBoxWrapper->removeFromParent(); + delete m_inlineBoxWrapper; + m_inlineBoxWrapper = nullptr; } LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const { if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent()) return LayoutRect(); - LayoutRect r = visualOverflowRect(); - // FIXME: layoutDelta needs to be applied in parts before/after transforms and // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308 r.move(view().layoutDelta()); - - // We have to use maximalOutlineSize() because a child might have an outline - // that projects outside of our overflowRect. - ASSERT(style().outlineSize() <= view().maximalOutlineSize()); - r.inflate(view().maximalOutlineSize()); - - computeRectForRepaint(repaintContainer, r); - return r; + return computeRectForRepaint(r, repaintContainer); } -void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const +bool RenderBox::shouldApplyClipAndScrollPositionForRepaint(const RenderLayerModelObject* repaintContainer) const +{ +#if PLATFORM(IOS) + if (!repaintContainer || repaintContainer != this) + return true; + + return !hasLayer() || !layer()->usesCompositedScrolling(); +#else + UNUSED_PARAM(repaintContainer); + return true; +#endif +} + +LayoutRect RenderBox::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, RepaintContext context) const { // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space. // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate @@ -2091,67 +2238,99 @@ void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintConta // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the // physical coordinate space of the repaintContainer. + LayoutRect adjustedRect = rect; const RenderStyle& styleToUse = style(); // LayoutState is only valid for root-relative, non-fixed position repainting if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) { LayoutState* layoutState = view().layoutState(); if (layer() && layer()->transform()) - rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect)); + adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor())); // We can't trust the bits on RenderObject, because this might be called while re-resolving style. if (styleToUse.hasInFlowPosition() && layer()) - rect.move(layer()->offsetForInFlowPosition()); + adjustedRect.move(layer()->offsetForInFlowPosition()); - rect.moveBy(location()); - rect.move(layoutState->m_paintOffset); + adjustedRect.moveBy(location()); + adjustedRect.move(layoutState->m_paintOffset); if (layoutState->m_clipped) - rect.intersect(layoutState->m_clipRect); - return; + adjustedRect.intersect(layoutState->m_clipRect); + return adjustedRect; } if (hasReflection()) - rect.unite(reflectedRect(rect)); + adjustedRect.unite(reflectedRect(adjustedRect)); if (repaintContainer == this) { if (repaintContainer->style().isFlippedBlocksWritingMode()) - flipForWritingMode(rect); - return; + flipForWritingMode(adjustedRect); + return adjustedRect; } - bool containerSkipped; - auto o = container(repaintContainer, &containerSkipped); - if (!o) - return; - - if (o->isRenderFlowThread()) { - RenderRegion* firstRegion = 0; - RenderRegion* lastRegion = 0; - toRenderFlowThread(o)->getRegionRangeForBox(this, firstRegion, lastRegion); - if (firstRegion) - rect.moveBy(firstRegion->flowThreadPortionRect().location()); + bool repaintContainerIsSkipped; + auto* container = this->container(repaintContainer, repaintContainerIsSkipped); + if (!container) + return adjustedRect; + + // This code isn't necessary for in-flow RenderFlowThreads. + // Don't add the location of the region in the flow thread for absolute positioned + // elements because their absolute position already pushes them down through + // the regions so adding this here and then adding the topLeft again would cause + // us to add the height twice. + // The same logic applies for elements flowed directly into the flow thread. Their topLeft member + // will already contain the portion rect of the region. + EPosition position = styleToUse.position(); + if (container->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) { + RenderRegion* firstRegion = nullptr; + RenderRegion* lastRegion = nullptr; + if (downcast<RenderFlowThread>(*container).getRegionRangeForBox(this, firstRegion, lastRegion)) + adjustedRect.moveBy(firstRegion->flowThreadPortionRect().location()); } - if (isWritingModeRoot() && !isOutOfFlowPositioned()) - flipForWritingMode(rect); + if (isWritingModeRoot()) { + if (!isOutOfFlowPositioned() || !context.m_dirtyRectIsFlipped) { + flipForWritingMode(adjustedRect); + context.m_dirtyRectIsFlipped = true; + } + } - LayoutPoint topLeft = rect.location(); - topLeft.move(locationOffset()); + LayoutSize locationOffset = this->locationOffset(); + // FIXME: This is needed as long as RenderWidget snaps to integral size/position. + if (isRenderReplaced() && isWidget()) { + LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset)); + adjustedRect.expand(locationOffset - flooredLocationOffset); + locationOffset = flooredLocationOffset; + } + + if (is<RenderMultiColumnFlowThread>(this)) { + // We won't normally run this code. Only when the repaintContainer is null (i.e., we're trying + // to get the rect in view coordinates) will we come in here, since normally repaintContainer + // will be set and we'll stop at the flow thread. This case is mainly hit by the check for whether + // or not images should animate. + // FIXME: Just as with offsetFromContainer, we aren't really handling objects that span + // multiple columns properly. + LayoutPoint physicalPoint(flipForWritingMode(adjustedRect.location())); + if (auto* region = downcast<RenderMultiColumnFlowThread>(*this).physicalTranslationFromFlowToRegion((physicalPoint))) { + adjustedRect.setLocation(region->flipForWritingMode(physicalPoint)); + return region->computeRectForRepaint(adjustedRect, repaintContainer, context); + } + } - EPosition position = styleToUse.position(); + LayoutPoint topLeft = adjustedRect.location(); + topLeft.move(locationOffset); - // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box + // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box // in the parent's coordinate space that encloses us. if (hasLayer() && layer()->transform()) { - fixed = position == FixedPosition; - rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect)); - topLeft = rect.location(); - topLeft.move(locationOffset()); + context.m_hasPositionFixedDescendant = position == FixedPosition; + adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor())); + topLeft = adjustedRect.location(); + topLeft.move(locationOffset); } else if (position == FixedPosition) - fixed = true; + context.m_hasPositionFixedDescendant = true; - if (position == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline()) - topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(this); + if (position == AbsolutePosition && container->isInFlowPositioned() && is<RenderInline>(*container)) + topLeft += downcast<RenderInline>(*container).offsetForInFlowPositionedInline(this); else if (styleToUse.hasInFlowPosition() && layer()) { // Apply the relative position offset when invalidating a rectangle. The layer // is translated, but the render box isn't, so we need to do this to get the @@ -2159,38 +2338,26 @@ void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintConta // flag on the RenderObject has been cleared, so use the one on the style(). topLeft += layer()->offsetForInFlowPosition(); } - - if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) { - LayoutRect repaintRect(topLeft, rect.size()); - toRenderBlock(o)->adjustRectForColumns(repaintRect); - topLeft = repaintRect.location(); - rect = repaintRect; - } // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout, // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer. - rect.setLocation(topLeft); - if (o->hasOverflowClip()) { - RenderBox* containerBox = toRenderBox(o); -#if PLATFORM(IOS) - if (!containerBox->layer() || !containerBox->layer()->hasAcceleratedTouchScrolling()) { -#endif - containerBox->applyCachedClipAndScrollOffsetForRepaint(rect); - if (rect.isEmpty()) - return; -#if PLATFORM(IOS) - } -#endif + adjustedRect.setLocation(topLeft); + if (container->hasOverflowClip()) { + RenderBox& containerBox = downcast<RenderBox>(*container); + if (containerBox.shouldApplyClipAndScrollPositionForRepaint(repaintContainer)) { + containerBox.applyCachedClipAndScrollPositionForRepaint(adjustedRect); + if (adjustedRect.isEmpty()) + return adjustedRect; + } } - if (containerSkipped) { - // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates. - LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o); - rect.move(-containerOffset); - return; + if (repaintContainerIsSkipped) { + // If the repaintContainer is below container, then we need to map the rect into repaintContainer's coordinates. + LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container); + adjustedRect.move(-containerOffset); + return adjustedRect; } - - o->computeRectForRepaint(repaintContainer, rect, fixed); + return container->computeRectForRepaint(adjustedRect, repaintContainer, context); } void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect) @@ -2238,14 +2405,14 @@ void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& compute } // If layout is limited to a subtree, the subtree root's logical width does not change. - if (element() && view().frameView().layoutRoot(true) == this) + if (element() && !view().frameView().layoutPending() && view().frameView().layoutRoot() == this) return; // The parent box is flexing us, so it has increased or decreased our // width. Use the width from the style context. // FIXME: Account for block-flow in flexible boxes. // https://bugs.webkit.org/show_bug.cgi?id=46418 - if (hasOverrideWidth() && (style().borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) { + if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()))) { computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth(); return; } @@ -2254,15 +2421,18 @@ void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& compute // https://bugs.webkit.org/show_bug.cgi?id=46418 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL); bool stretching = (parent()->style().boxAlign() == BSTRETCH); + // FIXME: Stretching is the only reason why we don't want the box to be treated as a replaced element, so we could perhaps + // refactor all this logic, not only for flex and grid since alignment is intended to be applied to any block. bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching); + treatAsReplaced = treatAsReplaced && (!isGridItem() || !hasStretchedLogicalWidth()); const RenderStyle& styleToUse = style(); Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth(); - RenderBlock* cb = containingBlock(); + RenderBlock& cb = *containingBlock(); LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region)); - bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode(); - + bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode(); + if (isInline() && !isInlineBlockOrInlineTable()) { // just calculate margins computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth); @@ -2272,13 +2442,14 @@ void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& compute return; } + LayoutUnit containerWidthInInlineDirection = containerLogicalWidth; + if (hasPerpendicularContainingBlock) + containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight(); + // Width calculations - if (treatAsReplaced) + if (treatAsReplaced) { computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth(); - else { - LayoutUnit containerWidthInInlineDirection = containerLogicalWidth; - if (hasPerpendicularContainingBlock) - containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight(); + } else { LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region); computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region); } @@ -2289,18 +2460,24 @@ void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& compute computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth); } else { LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth; - if (avoidsFloats() && cb->containsFloats()) + if (avoidsFloats() && cb.containsFloats()) containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region); - bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection(); + bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection(); computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent, hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start, hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end); } if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end) - && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated() && !cb->isRenderGrid()) { - LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this); - bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection(); + && !isFloating() && !isInline() && !cb.isFlexibleBoxIncludingDeprecated() +#if ENABLE(MATHML) + // RenderMathMLBlocks take the size of their content so we must not adjust the margin to fill the container size. + && !cb.isRenderMathMLBlock() +#endif + && !cb.isRenderGrid() + ) { + LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb.marginStartForChild(*this); + bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection(); if (hasInvertedDirection) computedValues.m_margins.m_start = newMargin; else @@ -2325,7 +2502,7 @@ LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, Lay LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const { if (logicalWidthLength.type() == FillAvailable) - return fillAvailableMeasure(availableLogicalWidth); + return std::max(borderAndPadding, fillAvailableMeasure(availableLogicalWidth)); LayoutUnit minLogicalWidth = 0; LayoutUnit maxLogicalWidth = 0; @@ -2348,8 +2525,12 @@ LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLengt } LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth, - const RenderBlock* cb, RenderRegion* region) const + const RenderBlock& cb, RenderRegion* region) const { + ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto()); + if (widthType == MinSize && logicalWidth.isAuto()) + return adjustBorderBoxLogicalWidthForBoxSizing(0); + if (!logicalWidth.isIntrinsicOrAuto()) { // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead. return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth)); @@ -2362,7 +2543,7 @@ LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Lengt LayoutUnit marginEnd = 0; LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd); - if (shrinkToAvoidFloats() && cb->containsFloats()) + if (shrinkToAvoidFloats() && cb.containsFloats()) logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region)); if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType)) @@ -2373,7 +2554,7 @@ LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Lengt static bool flexItemHasStretchAlignment(const RenderBox& flexitem) { auto parent = flexitem.parent(); - return flexitem.style().alignSelf() == AlignStretch || (flexitem.style().alignSelf() == AlignAuto && parent->style().alignItems() == AlignStretch); + return flexitem.style().resolvedAlignSelf(parent->style(), ItemPositionStretch).position() == ItemPositionStretch; } static bool isStretchingColumnFlexItem(const RenderBox& flexitem) @@ -2388,13 +2569,37 @@ static bool isStretchingColumnFlexItem(const RenderBox& flexitem) return false; } +// FIXME: Can/Should we move this inside specific layout classes (flex. grid)? Can we refactor columnFlexItemHasStretchAlignment logic? +bool RenderBox::hasStretchedLogicalWidth() const +{ + auto& style = this->style(); + if (!style.logicalWidth().isAuto() || style.marginStart().isAuto() || style.marginEnd().isAuto()) + return false; + RenderBlock* containingBlock = this->containingBlock(); + if (!containingBlock) { + // We are evaluating align-self/justify-self, which default to 'normal' for the root element. + // The 'normal' value behaves like 'start' except for Flexbox Items, which obviously should have a container. + return false; + } + if (containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode()) + return style.resolvedAlignSelf(containingBlock->style(), ItemPositionStretch).position() == ItemPositionStretch; + return style.resolvedJustifySelf(containingBlock->style(), ItemPositionStretch).position() == ItemPositionStretch; +} + bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const { + // Anonymous inline blocks always fill the width of their containing block. + if (isAnonymousInlineBlock()) + return false; + // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks, // but they allow text to sit on the same line as the marquee. if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee())) return true; + if (isGridItem()) + return !hasStretchedLogicalWidth(); + // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both // min-width and width. max-width is only clamped if it is also intrinsic. Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth(); @@ -2406,15 +2611,21 @@ bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const // FIXME: Think about block-flow here. Need to find out how marquee direction relates to // block-flow (as well as how marquee overflow should relate to block flow). // https://bugs.webkit.org/show_bug.cgi?id=46472 - if (parent()->style().overflowX() == OMARQUEE) { + if (parent()->isHTMLMarquee()) { EMarqueeDirection dir = parent()->style().marqueeDirection(); if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT) return true; } +#if ENABLE(MATHML) + // RenderMathMLBlocks take the size of their content, not of their container. + if (parent()->isRenderMathMLBlock()) + return true; +#endif + // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths. - // In the case of columns that have a stretch alignment, we go ahead and layout at the - // stretched size to avoid an extra layout when applying alignment. + // In the case of columns that have a stretch alignment, we layout at the stretched size + // to avoid an extra layout when applying alignment. if (parent()->isFlexibleBox()) { // For multiline columns, we need to apply align-content first, so we can't stretch now. if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap) @@ -2434,7 +2645,7 @@ bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const // stretching column flexbox. // FIXME: Think about block-flow here. // https://bugs.webkit.org/show_bug.cgi?id=46473 - if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (isHTMLInputElement(element()) || element()->hasTagName(selectTag) || element()->hasTagName(buttonTag) || isHTMLTextAreaElement(element()) || element()->hasTagName(legendTag))) + if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element()))) return true; if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode()) @@ -2443,9 +2654,9 @@ bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const return false; } -void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const +void RenderBox::computeInlineDirectionMargins(const RenderBlock& containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const { - const RenderStyle& containingBlockStyle = containingBlock->style(); + const RenderStyle& containingBlockStyle = containingBlock.style(); Length marginStartLength = style().marginStartUsing(&containingBlockStyle); Length marginEndLength = style().marginEndUsing(&containingBlockStyle); @@ -2458,7 +2669,7 @@ void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, Layo // Case One: The object is being centered in the containing block's available logical width. if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth) - || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) { + || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock.style().textAlign() == WEBKIT_CENTER)) { // Other browsers center the margin box for align=center elements so we match them here. LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth); LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth); @@ -2478,7 +2689,7 @@ void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, Layo // Case Three: The object is being pushed to the end of the containing block's available logical width. bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT) || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT)); - if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) { + if ((marginStartLength.isAuto() || pushToEndFromTextAlign) && childWidth < containerWidth) { marginEnd = valueForLength(marginEndLength, containerWidth); marginStart = containerWidth - childWidth - marginEnd; return; @@ -2494,7 +2705,7 @@ RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, Render { // Make sure nobody is trying to call this with a null region. if (!region) - return 0; + return nullptr; // If we have computed our width in this region already, it will be cached, and we can // just return it. @@ -2506,17 +2717,17 @@ RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, Render // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand // support to cover all boxes. RenderFlowThread* flowThread = flowThreadContainingBlock(); - if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode()) - return 0; + if (isRenderFlowThread() || !is<RenderNamedFlowThread>(flowThread) || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode()) + return nullptr; LogicalExtentComputedValues computedValues; computeLogicalWidthInRegion(computedValues, region); // Now determine the insets based off where this object is supposed to be positioned. - RenderBlock* cb = containingBlock(); - RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region); - RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion); - LayoutUnit containingBlockLogicalWidth = cb->logicalWidth(); + RenderBlock& cb = *containingBlock(); + RenderRegion* clampedContainingBlockRegion = cb.clampToStartAndEndRegions(region); + RenderBoxRegionInfo* containingBlockInfo = cb.renderBoxRegionInfo(clampedContainingBlockRegion); + LayoutUnit containingBlockLogicalWidth = cb.logicalWidth(); LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth; LayoutUnit marginStartInRegion = computedValues.m_margins.m_start; @@ -2531,15 +2742,15 @@ RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, Render LayoutUnit logicalLeftOffset = 0; - if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) { - LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region); - if (cb->style().isLeftToRightDirection()) + if (!isOutOfFlowPositioned() && avoidsFloats() && cb.containsFloats()) { + LayoutUnit startPositionDelta = cb.computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region); + if (cb.style().isLeftToRightDirection()) logicalLeftDelta += startPositionDelta; else logicalRightDelta += startPositionDelta; } - if (cb->style().isLeftToRightDirection()) + if (cb.style().isLeftToRightDirection()) logicalLeftOffset += logicalLeftDelta; else logicalLeftOffset -= (widthDelta + logicalRightDelta); @@ -2583,33 +2794,32 @@ static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle void RenderBox::updateLogicalHeight() { - LogicalExtentComputedValues computedValues; - computeLogicalHeight(logicalHeight(), logicalTop(), computedValues); - + auto computedValues = computeLogicalHeight(logicalHeight(), logicalTop()); setLogicalHeight(computedValues.m_extent); setLogicalTop(computedValues.m_position); setMarginBefore(computedValues.m_margins.m_before); setMarginAfter(computedValues.m_margins.m_after); } -void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const +RenderBox::LogicalExtentComputedValues RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const { + LogicalExtentComputedValues computedValues; computedValues.m_extent = logicalHeight; computedValues.m_position = logicalTop; // Cell height is managed by the table and inline non-replaced elements do not support a height property. if (isTableCell() || (isInline() && !isReplaced())) - return; + return computedValues; Length h; if (isOutOfFlowPositioned()) computePositionedLogicalHeight(computedValues); else { - RenderBlock* cb = containingBlock(); - bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode(); + RenderBlock& cb = *containingBlock(); + bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode(); if (!hasPerpendicularContainingBlock) { - bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode(); + bool shouldFlipBeforeAfter = cb.style().writingMode() != style().writingMode(); computeBlockDirectionMargins(cb, shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before, shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after); @@ -2618,12 +2828,12 @@ void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logica // For tables, calculate margins only. if (isTable()) { if (hasPerpendicularContainingBlock) { - bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style()); + bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style()); computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before, shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after); } - return; + return computedValues; } // FIXME: Account for block-flow in flexible boxes. @@ -2637,9 +2847,9 @@ void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logica // grab our cached flexible height. // FIXME: Account for block-flow in flexible boxes. // https://bugs.webkit.org/show_bug.cgi?id=46418 - if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated()) + if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid())) { h = Length(overrideLogicalContentHeight(), Fixed); - else if (treatAsReplaced) + } else if (treatAsReplaced) h = Length(computeReplacedLogicalHeight(), Fixed); else { h = style().logicalHeight(); @@ -2649,29 +2859,29 @@ void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logica // Block children of horizontal flexible boxes fill the height of the box. // FIXME: Account for block-flow in flexible boxes. // https://bugs.webkit.org/show_bug.cgi?id=46418 - if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL - && parent()->isStretchingChildren()) { + if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL + && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) { h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed); checkMinMaxHeight = false; } LayoutUnit heightResult; if (checkMinMaxHeight) { - heightResult = computeLogicalHeightUsing(style().logicalHeight()); - if (heightResult == -1) - heightResult = computedValues.m_extent; - heightResult = constrainLogicalHeightByMinMax(heightResult); + LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight(); + heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).value_or(computedValues.m_extent); + heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight); } else { // The only times we don't check min/max height are when a fixed length has // been given as an override. Just use that. The value has already been adjusted // for box-sizing. + ASSERT(h.isFixed()); heightResult = h.value() + borderAndPaddingLogicalHeight(); } computedValues.m_extent = heightResult; - + if (hasPerpendicularContainingBlock) { - bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style()); + bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style()); computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult, shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before, shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after); @@ -2683,66 +2893,105 @@ void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logica // is specified. When we're printing, we also need this quirk if the body or root has a percentage // height since we don't set a height in RenderView when we're printing. So without this quirk, the // height has nothing to be a percentage of, and it ends up being 0. That is bad. - bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent() - && (isRoot() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercent())) && !isInline(); + bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated() + && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline(); if (stretchesToViewport() || paginatedContentNeedsBaseHeight) { LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter(); LayoutUnit visibleHeight = view().pageOrViewLogicalHeight(); - if (isRoot()) + if (isDocumentElementRenderer()) computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins); else { LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight(); computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding); } } + return computedValues; } -LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height) const +std::optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const { - LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height); - if (logicalHeight != -1) - logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight); - return logicalHeight; + if (std::optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight)) + return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value()); + return std::nullopt; +} + +std::optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const +{ + if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight)) + return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight()); + return std::nullopt; } -LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height) const +std::optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, std::optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const { - LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height); - if (heightIncludingScrollbar == -1) - return -1; - return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight()); + // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to. + // If that happens, this code will have to change. + if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) { + if (!intrinsicContentHeight) + return intrinsicContentHeight; + if (style().boxSizing() == BORDER_BOX) + return intrinsicContentHeight.value() + borderAndPaddingLogicalHeight(); + return intrinsicContentHeight; + } + if (logicalHeightLength.isFillAvailable()) + return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding; + ASSERT_NOT_REACHED(); + return LayoutUnit(0); } -LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height) const +std::optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const { + if (height.isAuto()) + return heightType == MinSize ? std::optional<LayoutUnit>(0) : std::nullopt; + // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to. + // If that happens, this code will have to change. + if (height.isIntrinsic()) + return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight()); if (height.isFixed()) - return height.value(); - if (height.isPercent()) + return LayoutUnit(height.value()); + if (height.isPercentOrCalculated()) return computePercentageLogicalHeight(height); - if (height.isViewportPercentage()) - return valueForLength(height, 0); - return -1; + return std::nullopt; } -bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const +bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox& containingBlock, bool isPerpendicularWritingMode) const { + // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM, + // and percent heights of children should be resolved against the multicol or paged container. + if (containingBlock.isInFlowRenderFlowThread() && !isPerpendicularWritingMode) + return true; + // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages. // For standards mode, we treat the percentage as auto if it has an auto-height containing block. - if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock()) + if (!document().inQuirksMode() && !containingBlock.isAnonymousBlock()) return false; - return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode(); + return !containingBlock.isTableCell() && !containingBlock.isOutOfFlowPositioned() && containingBlock.style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode(); } -LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const +static bool tableCellShouldHaveZeroInitialSize(const RenderBlock& block, bool scrollsOverflowY) { - LayoutUnit availableHeight = -1; - + // Normally we would let the cell size intrinsically, but scrolling overflow has to be + // treated differently, since WinIE lets scrolled overflow regions shrink as needed. + // While we can't get all cases right, we can at least detect when the cell has a specified + // height or when the table has a specified height. In these cases we want to initially have + // no size and allow the flexing of the table or the cell to its specified height to cause us + // to grow to fill the space. This could end up being wrong in some cases, but it is + // preferable to the alternative (sizing intrinsically and making the row end up too big). + const RenderTableCell& cell = downcast<RenderTableCell>(block); + return scrollsOverflowY && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto()); +} + +std::optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const +{ + std::optional<LayoutUnit> availableHeight; + bool skippedAutoHeightContainingBlock = false; RenderBlock* cb = containingBlock(); const RenderBox* containingBlockChild = this; LayoutUnit rootMarginBorderPaddingHeight = 0; - while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) { - if (cb->isBody() || cb->isRoot()) + bool isHorizontal = isHorizontalWritingMode(); + while (cb && !is<RenderView>(*cb) && skipContainingBlockForPercentHeightCalculation(*cb, isHorizontal != cb->isHorizontalWritingMode())) { + if (cb->isBody() || cb->isDocumentElementRenderer()) rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight(); skippedAutoHeightContainingBlock = true; containingBlockChild = cb; @@ -2758,72 +3007,49 @@ LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const bool includeBorderPadding = isTable(); - if (isHorizontalWritingMode() != cb->isHorizontalWritingMode()) + if (isHorizontal != cb->isHorizontalWritingMode()) availableHeight = containingBlockChild->containingBlockLogicalWidthForContent(); else if (hasOverrideContainingBlockLogicalHeight()) availableHeight = overrideContainingBlockContentLogicalHeight(); - else if (cb->isTableCell()) { + else if (cb->isGridItem() && cb->hasOverrideLogicalContentHeight()) + availableHeight = cb->overrideLogicalContentHeight(); + else if (is<RenderTableCell>(*cb)) { if (!skippedAutoHeightContainingBlock) { // Table cells violate what the CSS spec says to do with heights. Basically we // don't care if the cell specified a height or not. We just always make ourselves // be a percentage of the cell's current content height. - if (!cb->hasOverrideHeight()) { - // Normally we would let the cell size intrinsically, but scrolling overflow has to be - // treated differently, since WinIE lets scrolled overflow regions shrink as needed. - // While we can't get all cases right, we can at least detect when the cell has a specified - // height or when the table has a specified height. In these cases we want to initially have - // no size and allow the flexing of the table or the cell to its specified height to cause us - // to grow to fill the space. This could end up being wrong in some cases, but it is - // preferable to the alternative (sizing intrinsically and making the row end up too big). - RenderTableCell* cell = toRenderTableCell(cb); - if (scrollsOverflowY() && (!cell->style().logicalHeight().isAuto() || !cell->table()->style().logicalHeight().isAuto())) - return 0; - return -1; - } + if (!cb->hasOverrideLogicalContentHeight()) + return tableCellShouldHaveZeroInitialSize(*cb, scrollsOverflowY()) ? std::optional<LayoutUnit>(0) : std::nullopt; + availableHeight = cb->overrideLogicalContentHeight(); includeBorderPadding = true; } } else if (cbstyle.logicalHeight().isFixed()) { - LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle.logicalHeight().value()); - availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight())); - } else if (cbstyle.logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) { + LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(cbstyle.logicalHeight().value())); + availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), std::nullopt)); + } else if (cbstyle.logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) { // We need to recur and compute the percentage height for our containing block. - LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight()); - if (heightWithScrollbar != -1) { + if (std::optional<LayoutUnit> heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight())) { LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar); // We need to adjust for min/max height because this method does not // handle the min/max of the current block, its caller does. So the // return value from the recursive call will not have been adjusted // yet. - LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight()); - availableHeight = std::max<LayoutUnit>(0, contentBoxHeight); - } - } else if (cbstyle.logicalHeight().isViewportPercentage()) { - LayoutUnit heightWithScrollbar = valueForLength(cbstyle.logicalHeight(), 0, &view()); - if (heightWithScrollbar != -1) { - LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar); - // We need to adjust for min/max height because this method does - // not handle the min/max of the current block, its caller does. - // So the return value from the recursive call will not have been - // adjusted yet. - LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight()); + LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), std::nullopt); availableHeight = std::max<LayoutUnit>(0, contentBoxHeight); } } else if (isOutOfFlowPositionedWithSpecifiedHeight) { // Don't allow this to affect the block' height() member variable, since this // can get called while the block is still laying out its kids. - LogicalExtentComputedValues computedValues; - cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues); + auto computedValues = cb->computeLogicalHeight(cb->logicalHeight(), 0); availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight(); } else if (cb->isRenderView()) availableHeight = view().pageOrViewLogicalHeight(); - if (availableHeight == -1) + if (!availableHeight) return availableHeight; - availableHeight -= rootMarginBorderPaddingHeight; - - LayoutUnit result = valueForLength(height, availableHeight); + LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight); if (includeBorderPadding) { // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack. // It is necessary to use the border-box to match WinIE's broken @@ -2837,18 +3063,26 @@ LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const { - return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style().logicalWidth()), shouldComputePreferred); + return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred); } LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const { - LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercent()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMinWidth()); - LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercent()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMaxWidth()); + auto& logicalMinWidth = style().logicalMinWidth(); + auto& logicalMaxWidth = style().logicalMaxWidth(); + bool useLogicalWidthForMinWidth = (shouldComputePreferred == ComputePreferred && logicalMinWidth.isPercentOrCalculated()) || logicalMinWidth.isUndefined(); + bool useLogicalWidthForMaxWidth = (shouldComputePreferred == ComputePreferred && logicalMaxWidth.isPercentOrCalculated()) || logicalMaxWidth.isUndefined(); + auto minLogicalWidth = useLogicalWidthForMinWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, logicalMinWidth); + auto maxLogicalWidth = useLogicalWidthForMaxWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, logicalMaxWidth); return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth)); } -LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const +LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const { + ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto()); + if (widthType == MinSize && logicalWidth.isAuto()) + return adjustContentBoxLogicalWidthForBoxSizing(0); + switch (logicalWidth.type()) { case Fixed: return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value()); @@ -2858,11 +3092,6 @@ LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) cons LayoutUnit availableLogicalWidth = 0; return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth(); } - case ViewportPercentageWidth: - case ViewportPercentageHeight: - case ViewportPercentageMin: - case ViewportPercentageMax: - return adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, 0)); case FitContent: case FillAvailable: case Percent: @@ -2870,13 +3099,13 @@ LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) cons // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the // containing block's block-flow. // https://bugs.webkit.org/show_bug.cgi?id=46496 - const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent(); + const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(*container())) : containingBlockLogicalWidthForContent(); Length containerLogicalWidth = containingBlock()->style().logicalWidth(); // FIXME: Handle cases when containing block width is calculated or viewport percent. // https://bugs.webkit.org/show_bug.cgi?id=91071 if (logicalWidth.isIntrinsic()) return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth(); - if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent()))) + if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated()))) return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw)); } FALLTHROUGH; @@ -2892,41 +3121,49 @@ LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) cons return 0; } -LayoutUnit RenderBox::computeReplacedLogicalHeight() const +LayoutUnit RenderBox::computeReplacedLogicalHeight(std::optional<LayoutUnit>) const { - return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style().logicalHeight())); + return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight())); } LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const { - LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style().logicalMinHeight()); - LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style().logicalMaxHeight()); + LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight()); + LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight()); return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight)); } -LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const +LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const { + ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto()); + if (heightType == MinSize && logicalHeight.isAuto()) + return adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit>(0)); + switch (logicalHeight.type()) { case Fixed: - return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value()); + return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value())); case Percent: case Calculated: { - auto cb = isOutOfFlowPositioned() ? container() : containingBlock(); - while (cb->isAnonymous() && !cb->isRenderView()) { - cb = cb->containingBlock(); - toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox&>(*this)); + auto* container = isOutOfFlowPositioned() ? this->container() : containingBlock(); + while (container && container->isAnonymous()) { + // Stop at rendering context root. + if (is<RenderView>(*container) || is<RenderNamedFlowThread>(*container)) + break; + container = container->containingBlock(); + downcast<RenderBlock>(*container).addPercentHeightDescendant(const_cast<RenderBox&>(*this)); } // FIXME: This calculation is not patched for block-flow yet. // https://bugs.webkit.org/show_bug.cgi?id=46500 - if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) { - ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock()); - RenderBlock* block = toRenderBlock(cb); - LogicalExtentComputedValues computedValues; - block->computeLogicalHeight(block->logicalHeight(), 0, computedValues); - LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight(); - LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight); + if (container->isOutOfFlowPositioned() + && container->style().height().isAuto() + && !(container->style().top().isAuto() || container->style().bottom().isAuto())) { + ASSERT_WITH_SECURITY_IMPLICATION(container->isRenderBlock()); + auto& block = downcast<RenderBlock>(*container); + auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0); + LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight(); + LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight); return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight)); } @@ -2935,7 +3172,7 @@ LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) co // https://bugs.webkit.org/show_bug.cgi?id=46496 LayoutUnit availableHeight; if (isOutOfFlowPositioned()) - availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb)); + availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*container)); else { availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding); // It is necessary to use the border-box to match WinIE's broken @@ -2943,24 +3180,25 @@ LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) co // table cells using percentage heights. // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right. // https://bugs.webkit.org/show_bug.cgi?id=46997 - while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercent())) { - if (cb->isTableCell()) { + while (container && !is<RenderView>(*container) + && (container->style().logicalHeight().isAuto() || container->style().logicalHeight().isPercentOrCalculated())) { + if (container->isTableCell()) { // Don't let table cells squeeze percent-height replaced elements // <http://bugs.webkit.org/show_bug.cgi?id=15359> availableHeight = std::max(availableHeight, intrinsicLogicalHeight()); return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight()); } - toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox&>(*this)); - cb = cb->containingBlock(); + downcast<RenderBlock>(*container).addPercentHeightDescendant(const_cast<RenderBox&>(*this)); + container = container->containingBlock(); } } return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight)); } - case ViewportPercentageWidth: - case ViewportPercentageHeight: - case ViewportPercentageMin: - case ViewportPercentageMax: - return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, 0)); + case MinContent: + case MaxContent: + case FitContent: + case FillAvailable: + return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight())); default: return intrinsicLogicalHeight(); } @@ -2968,7 +3206,7 @@ LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) co LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const { - return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType)); + return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), std::nullopt); } LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const @@ -2976,29 +3214,27 @@ LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogi // We need to stop here, since we don't want to increase the height of the table // artificially. We're going to rely on this cell getting expanded to some new // height, and then when we lay out again we'll use the calculation below. - if (isTableCell() && (h.isAuto() || h.isPercent())) { - if (hasOverrideHeight()) + if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) { + if (hasOverrideLogicalContentHeight()) return overrideLogicalContentHeight(); return logicalHeight() - borderAndPaddingLogicalHeight(); } - if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) { + if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) { // FIXME: This is wrong if the containingBlock has a perpendicular writing mode. - LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock()); + LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock()); return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight)); } - LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h); - if (heightIncludingScrollbar != -1) + if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, std::nullopt)) return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight()); // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode. // https://bugs.webkit.org/show_bug.cgi?id=46500 - if (isRenderBlock() && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) { - RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this)); - LogicalExtentComputedValues computedValues; - block->computeLogicalHeight(block->logicalHeight(), 0, computedValues); - LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight(); + if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) { + RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this)); + auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0); + LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight(); return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight); } @@ -3011,7 +3247,7 @@ LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogi return availableHeight; } -void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const +void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const { if (isTableCell()) { // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though, @@ -3024,62 +3260,70 @@ void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, // Margins are calculated with respect to the logical width of // the containing block (8.3) LayoutUnit cw = containingBlockLogicalWidthForContent(); - const RenderStyle& containingBlockStyle = containingBlock->style(); + const RenderStyle& containingBlockStyle = containingBlock.style(); marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw); marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw); } -void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock) +void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock) { LayoutUnit marginBefore; LayoutUnit marginAfter; computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter); - containingBlock->setMarginBeforeForChild(*this, marginBefore); - containingBlock->setMarginAfterForChild(*this, marginAfter); + containingBlock.setMarginBeforeForChild(*this, marginBefore); + containingBlock.setMarginAfterForChild(*this, marginAfter); } -LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const +LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const { - if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode()) + if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode()) return containingBlockLogicalHeightForPositioned(containingBlock, false); - if (containingBlock->isBox()) { + if (hasOverrideContainingBlockLogicalWidth()) { + if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth()) + return overrideLogicalWidth.value(); + } + + if (is<RenderBox>(containingBlock)) { bool isFixedPosition = style().position() == FixedPosition; RenderFlowThread* flowThread = flowThreadContainingBlock(); if (!flowThread) { - if (isFixedPosition && containingBlock->isRenderView()) - return toRenderView(containingBlock)->clientLogicalWidthForFixedPosition(); + if (isFixedPosition && is<RenderView>(containingBlock)) + return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition(); - return toRenderBox(containingBlock)->clientLogicalWidth(); + return downcast<RenderBox>(containingBlock).clientLogicalWidth(); } - if (isFixedPosition && containingBlock->isRenderNamedFlowThread()) - return containingBlock->view().clientLogicalWidth(); + if (isFixedPosition && is<RenderNamedFlowThread>(containingBlock)) + return containingBlock.view().clientLogicalWidth(); + + if (!is<RenderBlock>(containingBlock)) + return downcast<RenderBox>(containingBlock).clientLogicalWidth(); - const RenderBlock* cb = toRenderBlock(containingBlock); - RenderBoxRegionInfo* boxInfo = 0; + const RenderBlock& cb = downcast<RenderBlock>(containingBlock); + RenderBoxRegionInfo* boxInfo = nullptr; if (!region) { - if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode) - return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion(); + if (is<RenderFlowThread>(containingBlock) && !checkForPerpendicularWritingMode) + return downcast<RenderFlowThread>(containingBlock).contentLogicalWidthOfFirstRegion(); if (isWritingModeRoot()) { - LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage(); - RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset); + LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage(); + RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset); if (cbRegion) - boxInfo = cb->renderBoxRegionInfo(cbRegion); + boxInfo = cb.renderBoxRegionInfo(cbRegion); } - } else if (region && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) { - RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region); - boxInfo = cb->renderBoxRegionInfo(containingBlockRegion); + } else if (flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) { + RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region); + boxInfo = cb.renderBoxRegionInfo(containingBlockRegion); } - return (boxInfo) ? std::max<LayoutUnit>(0, cb->clientLogicalWidth() - (cb->logicalWidth() - boxInfo->logicalWidth())) : cb->clientLogicalWidth(); + return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth(); } - ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned()); + ASSERT(containingBlock.isInFlowPositioned()); - const RenderInline* flow = toRenderInline(containingBlock); - InlineFlowBox* first = flow->firstLineBox(); - InlineFlowBox* last = flow->lastLineBox(); + const auto& flow = downcast<RenderInline>(containingBlock); + InlineFlowBox* first = flow.firstLineBox(); + InlineFlowBox* last = flow.lastLineBox(); // If the containing block is empty, return a width of 0. if (!first || !last) @@ -3087,7 +3331,7 @@ LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxMo LayoutUnit fromLeft; LayoutUnit fromRight; - if (containingBlock->style().isLeftToRightDirection()) { + if (containingBlock.style().isLeftToRightDirection()) { fromLeft = first->logicalLeft() + first->borderLogicalLeft(); fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight(); } else { @@ -3098,91 +3342,108 @@ LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxMo return std::max<LayoutUnit>(0, fromRight - fromLeft); } -LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const +LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const { - if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode()) - return containingBlockLogicalWidthForPositioned(containingBlock, 0, false); + if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode()) + return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false); + + if (hasOverrideContainingBlockLogicalHeight()) { + if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight()) + return overrideLogicalHeight.value(); + } - if (containingBlock->isBox()) { + if (containingBlock.isBox()) { bool isFixedPosition = style().position() == FixedPosition; - if (isFixedPosition && containingBlock->isRenderView()) - return toRenderView(containingBlock)->clientLogicalHeightForFixedPosition(); + if (isFixedPosition && is<RenderView>(containingBlock)) + return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition(); - const RenderBlock* cb = containingBlock->isRenderBlock() ? toRenderBlock(containingBlock) : containingBlock->containingBlock(); - LayoutUnit result = cb->clientLogicalHeight(); + const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock(); + LayoutUnit result = cb.clientLogicalHeight(); RenderFlowThread* flowThread = flowThreadContainingBlock(); - if (flowThread && containingBlock->isRenderFlowThread() && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) { - if (containingBlock->isRenderNamedFlowThread() && isFixedPosition) - return containingBlock->view().clientLogicalHeight(); - return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion(); + if (flowThread && is<RenderFlowThread>(containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) { + if (is<RenderNamedFlowThread>(containingBlock) && isFixedPosition) + return containingBlock.view().clientLogicalHeight(); + return downcast<RenderFlowThread>(containingBlock).contentLogicalHeightOfFirstRegion(); } return result; } - ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned()); + ASSERT(containingBlock.isInFlowPositioned()); - const RenderInline* flow = toRenderInline(containingBlock); - InlineFlowBox* first = flow->firstLineBox(); - InlineFlowBox* last = flow->lastLineBox(); + const auto& flow = downcast<RenderInline>(containingBlock); + InlineFlowBox* first = flow.firstLineBox(); + InlineFlowBox* last = flow.lastLineBox(); // If the containing block is empty, return a height of 0. if (!first || !last) return 0; LayoutUnit heightResult; - LayoutRect boundingBox = flow->linesBoundingBox(); - if (containingBlock->isHorizontalWritingMode()) + LayoutRect boundingBox = flow.linesBoundingBox(); + if (containingBlock.isHorizontalWritingMode()) heightResult = boundingBox.height(); else heightResult = boundingBox.width(); - heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter()); + heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter()); return heightResult; } -static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region) +static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region) { if (!logicalLeft.isAuto() || !logicalRight.isAuto()) return; // FIXME: The static distance computation has not been patched for mixed writing modes yet. if (child->parent()->style().direction() == LTR) { - LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft(); - for (auto curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) { - if (curr->isBox()) { - staticPosition += toRenderBox(curr)->logicalLeft(); - if (region && toRenderBox(curr)->isRenderBlock()) { - const RenderBlock* cb = toRenderBlock(curr); - region = cb->clampToStartAndEndRegions(region); - RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region); - if (boxInfo) - staticPosition += boxInfo->logicalLeft(); - } + LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft(); + for (auto* current = child->parent(); current && current != &containerBlock; current = current->container()) { + if (!is<RenderBox>(*current)) + continue; + const auto& renderBox = downcast<RenderBox>(*current); + staticPosition += renderBox.logicalLeft(); + if (renderBox.isInFlowPositioned()) + staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height(); + if (region && is<RenderBlock>(*current)) { + const RenderBlock& currentBlock = downcast<RenderBlock>(*current); + region = currentBlock.clampToStartAndEndRegions(region); + RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region); + if (boxInfo) + staticPosition += boxInfo->logicalLeft(); } } logicalLeft.setValue(Fixed, staticPosition); } else { - RenderBox* enclosingBox = child->parent()->enclosingBox(); - LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft(); - for (RenderElement* curr = enclosingBox; curr; curr = curr->container()) { - if (curr->isBox()) { - if (curr != containerBlock) - staticPosition -= toRenderBox(curr)->logicalLeft(); - if (curr == enclosingBox) - staticPosition -= enclosingBox->logicalWidth(); - if (region && curr->isRenderBlock()) { - const RenderBlock* cb = toRenderBlock(curr); - region = cb->clampToStartAndEndRegions(region); - RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region); - if (boxInfo) { - if (curr != containerBlock) - staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth()); - if (curr == enclosingBox) - staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth(); - } + LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock.borderLogicalLeft(); + auto& enclosingBox = child->parent()->enclosingBox(); + if (&enclosingBox != &containerBlock && containerBlock.isDescendantOf(&enclosingBox)) { + logicalRight.setValue(Fixed, staticPosition); + return; + } + + staticPosition -= enclosingBox.logicalWidth(); + for (const RenderElement* current = &enclosingBox; current; current = current->container()) { + if (!is<RenderBox>(*current)) + continue; + + if (current != &containerBlock) { + auto& renderBox = downcast<RenderBox>(*current); + staticPosition -= renderBox.logicalLeft(); + if (renderBox.isInFlowPositioned()) + staticPosition -= renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height(); + } + if (region && is<RenderBlock>(*current)) { + auto& currentBlock = downcast<RenderBlock>(*current); + region = currentBlock.clampToStartAndEndRegions(region); + RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region); + if (boxInfo) { + if (current != &containerBlock) + staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth()); + if (current == &enclosingBox) + staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth(); } } - if (curr == containerBlock) + if (current == &containerBlock) break; } logicalRight.setValue(Fixed, staticPosition); @@ -3216,14 +3477,14 @@ void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& compu // We don't use containingBlock(), since we may be positioned by an enclosing // relative positioned inline. - const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container()); + const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container()); const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region); // Use the container block's direction except when calculating the static distance // This conforms with the reference results for abspos-replaced-width-margin-000.htm // of the CSS 2.1 test suite - TextDirection containerDirection = containerBlock->style().direction(); + TextDirection containerDirection = containerBlock.style().direction(); bool isHorizontal = isHorizontalWritingMode(); const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth(); @@ -3262,7 +3523,7 @@ void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& compu computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region); // Calculate constraint equation values for 'width' case. - computePositionedLogicalWidthUsing(style().logicalWidth(), containerBlock, containerDirection, + computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection, containerLogicalWidth, bordersPlusPadding, logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight, computedValues); @@ -3271,7 +3532,7 @@ void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& compu if (!style().logicalMaxWidth().isUndefined()) { LogicalExtentComputedValues maxValues; - computePositionedLogicalWidthUsing(style().logicalMaxWidth(), containerBlock, containerDirection, + computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection, containerLogicalWidth, bordersPlusPadding, logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight, maxValues); @@ -3288,7 +3549,7 @@ void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& compu if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) { LogicalExtentComputedValues minValues; - computePositionedLogicalWidthUsing(style().logicalMinWidth(), containerBlock, containerDirection, + computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection, containerLogicalWidth, bordersPlusPadding, logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight, minValues); @@ -3301,19 +3562,27 @@ void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& compu } } + if (!style().hasStaticInlinePosition(isHorizontal)) + computedValues.m_position += extraInlineOffset(); + computedValues.m_extent += bordersPlusPadding; + if (is<RenderBox>(containerBlock)) { + auto& containingBox = downcast<RenderBox>(containerBlock); + if (containingBox.shouldPlaceBlockDirectionScrollbarOnLeft()) + computedValues.m_position += containingBox.verticalScrollbarWidth(); + } // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions. // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock. RenderFlowThread* flowThread = flowThreadContainingBlock(); - if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) { - ASSERT(containerBlock->canHaveBoxInfoInRegion()); + if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) { + ASSERT(containerBlock.canHaveBoxInfoInRegion()); LayoutUnit logicalLeftPos = computedValues.m_position; - const RenderBlock* cb = toRenderBlock(containerBlock); - LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage(); - RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset); + const RenderBlock& renderBlock = downcast<RenderBlock>(containerBlock); + LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage(); + RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset); if (cbRegion) { - RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion); + RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion); if (boxInfo) { logicalLeftPos += boxInfo->logicalLeft(); computedValues.m_position = logicalLeftPos; @@ -3322,23 +3591,26 @@ void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& compu } } -static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth) +static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth) { // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped // 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. - if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style().isFlippedBlocksWritingMode()) { + if (containerBlock.isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock.style().isFlippedBlocksWritingMode()) { logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos; - logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom()); + logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderRight() : containerBlock.borderBottom()); } else - logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop()); + logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderLeft() : containerBlock.borderTop()); } -void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection, +void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject& containerBlock, TextDirection containerDirection, LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding, Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight, LogicalExtentComputedValues& computedValues) const { - if (logicalWidth.isIntrinsic()) + ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto()); + if (widthType == MinSize && logicalWidth.isAuto()) + logicalWidth = Length(0, Fixed); + else if (logicalWidth.isIntrinsic()) logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed); // 'left' and 'right' cannot both be 'auto' because one would of been @@ -3347,7 +3619,7 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re LayoutUnit logicalLeftValue = 0; - const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false); + const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false); bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto(); bool logicalLeftIsAuto = logicalLeft.isAuto(); @@ -3501,10 +3773,10 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re // positioned, inline because right now, it is using the logical left position // of the first line box when really it should use the last line box. When // this is fixed elsewhere, this block should be removed. - if (containerBlock->isRenderInline() && !containerBlock->style().isLeftToRightDirection()) { - const RenderInline* flow = toRenderInline(containerBlock); - InlineFlowBox* firstLine = flow->firstLineBox(); - InlineFlowBox* lastLine = flow->lastLineBox(); + if (is<RenderInline>(containerBlock) && !containerBlock.style().isLeftToRightDirection()) { + const auto& flow = downcast<RenderInline>(containerBlock); + InlineFlowBox* firstLine = flow.firstLineBox(); + InlineFlowBox* lastLine = flow.lastLineBox(); if (firstLine && lastLine && firstLine != lastLine) { computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft()); return; @@ -3515,16 +3787,21 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth); } -static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock) +static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject& containerBlock) { if (!logicalTop.isAuto() || !logicalBottom.isAuto()) return; // FIXME: The static distance computation has not been patched for mixed writing modes. - LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore(); - for (RenderElement* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) { - if (curr->isBox() && !curr->isTableRow()) - staticLogicalTop += toRenderBox(curr)->logicalTop(); + LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock.borderBefore(); + for (RenderElement* container = child->parent(); container && container != &containerBlock; container = container->container()) { + if (!is<RenderBox>(*container)) + continue; + const auto& renderBox = downcast<RenderBox>(*container); + if (!is<RenderTableRow>(renderBox)) + staticLogicalTop += renderBox.logicalTop(); + if (renderBox.isInFlowPositioned()) + staticLogicalTop += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().height() : renderBox.offsetForInFlowPosition().width(); } logicalTop.setValue(Fixed, staticLogicalTop); } @@ -3544,7 +3821,7 @@ void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& comp // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline. - const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container()); + const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container()); const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock); @@ -3578,7 +3855,7 @@ void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& comp // Calculate constraint equation values for 'height' case. LayoutUnit logicalHeight = computedValues.m_extent; - computePositionedLogicalHeightUsing(styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight, + computePositionedLogicalHeightUsing(MainOrPreferredSize, styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight, logicalTopLength, logicalBottomLength, marginBefore, marginAfter, computedValues); @@ -3589,7 +3866,7 @@ void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& comp if (!styleToUse.logicalMaxHeight().isUndefined()) { LogicalExtentComputedValues maxValues; - computePositionedLogicalHeightUsing(styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight, + computePositionedLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight, logicalTopLength, logicalBottomLength, marginBefore, marginAfter, maxValues); @@ -3602,10 +3879,10 @@ void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& comp } // Calculate constraint equation values for 'min-height' case. - if (!styleToUse.logicalMinHeight().isZero()) { + if (!styleToUse.logicalMinHeight().isZero() || styleToUse.logicalMinHeight().isIntrinsic()) { LogicalExtentComputedValues minValues; - computePositionedLogicalHeightUsing(styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight, + computePositionedLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight, logicalTopLength, logicalBottomLength, marginBefore, marginAfter, minValues); @@ -3617,20 +3894,23 @@ void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& comp } } + if (!style().hasStaticBlockPosition(isHorizontalWritingMode())) + computedValues.m_position += extraBlockOffset(); + // Set final height value. computedValues.m_extent += bordersPlusPadding; // Adjust logicalTop if we need to for perpendicular writing modes in regions. // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock. RenderFlowThread* flowThread = flowThreadContainingBlock(); - if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) { - ASSERT(containerBlock->canHaveBoxInfoInRegion()); + if (flowThread && isHorizontalWritingMode() != containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) { + ASSERT(containerBlock.canHaveBoxInfoInRegion()); LayoutUnit logicalTopPos = computedValues.m_position; - const RenderBlock* cb = toRenderBlock(containerBlock); - LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft(); - RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset); + const RenderBlock& renderBox = downcast<RenderBlock>(containerBlock); + LayoutUnit cbPageOffset = renderBox.offsetFromLogicalTopOfFirstPage() - logicalLeft(); + RenderRegion* cbRegion = renderBox.regionAtBlockOffset(cbPageOffset); if (cbRegion) { - RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion); + RenderBoxRegionInfo* boxInfo = renderBox.renderBoxRegionInfo(cbRegion); if (boxInfo) { logicalTopPos += boxInfo->logicalLeft(); computedValues.m_position = logicalTopPos; @@ -3639,33 +3919,37 @@ void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& comp } } -static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight) +static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalHeight) { // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped // 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. - if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode()) - || (child->style().isFlippedBlocksWritingMode() != containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode())) + if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock.isHorizontalWritingMode()) + || (child->style().isFlippedBlocksWritingMode() != containerBlock.style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode())) logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos; // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt. - if (containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) { + if (containerBlock.style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode()) { if (child->isHorizontalWritingMode()) - logicalTopPos += containerBlock->borderBottom(); + logicalTopPos += containerBlock.borderBottom(); else - logicalTopPos += containerBlock->borderRight(); + logicalTopPos += containerBlock.borderRight(); } else { if (child->isHorizontalWritingMode()) - logicalTopPos += containerBlock->borderTop(); + logicalTopPos += containerBlock.borderTop(); else - logicalTopPos += containerBlock->borderLeft(); + logicalTopPos += containerBlock.borderLeft(); } } -void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock, +void RenderBox::computePositionedLogicalHeightUsing(SizeType heightType, Length logicalHeightLength, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight, Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter, LogicalExtentComputedValues& computedValues) const { + ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeightLength.isAuto()); + if (heightType == MinSize && logicalHeightLength.isAuto()) + logicalHeightLength = Length(0, Fixed); + // 'top' and 'bottom' cannot both be 'auto' because 'top would of been // converted to the static position in computePositionedLogicalHeight() ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto())); @@ -3673,7 +3957,7 @@ void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, LayoutUnit logicalHeightValue; LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding; - const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false); + const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false); LayoutUnit logicalTopValue = 0; @@ -3682,9 +3966,15 @@ void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, bool logicalBottomIsAuto = logicalBottom.isAuto(); // Height is never unsolved for tables. + LayoutUnit resolvedLogicalHeight; if (isTable()) { - logicalHeightLength.setValue(Fixed, contentLogicalHeight); + resolvedLogicalHeight = contentLogicalHeight; logicalHeightIsAuto = false; + } else { + if (logicalHeightLength.isIntrinsic()) + resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding).value(); + else + resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight)); } if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) { @@ -3699,7 +3989,7 @@ void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, // NOTE: It is not necessary to solve for 'bottom' in the over constrained // case because the value is not used for any further calculations. - logicalHeightValue = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight)); + logicalHeightValue = resolvedLogicalHeight; logicalTopValue = valueForLength(logicalTop, containerLogicalHeight); const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding); @@ -3766,7 +4056,7 @@ void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, logicalHeightValue = contentLogicalHeight; } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) { // RULE 4: (solve of top) - logicalHeightValue = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight)); + logicalHeightValue = resolvedLogicalHeight; logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight)); } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) { // RULE 5: (solve of height) @@ -3774,7 +4064,7 @@ void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, logicalHeightValue = std::max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight))); } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) { // RULE 6: (no need solve of bottom) - logicalHeightValue = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight)); + logicalHeightValue = resolvedLogicalHeight; logicalTopValue = valueForLength(logicalTop, containerLogicalHeight); } } @@ -3795,14 +4085,14 @@ void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValue // We don't use containingBlock(), since we may be positioned by an enclosing // relative positioned inline. - const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container()); + const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container()); const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock); - const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false); + const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false); // To match WinIE, in quirks mode use the parent's 'direction' property // instead of the the container block's. - TextDirection containerDirection = containerBlock->style().direction(); + TextDirection containerDirection = containerBlock.style().direction(); // Variables to solve. bool isHorizontal = isHorizontalWritingMode(); @@ -3830,7 +4120,7 @@ void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValue * else if 'direction' is 'rtl', set 'right' to the static position. \*-----------------------------------------------------------------------*/ // see FIXME 1 - computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, 0); // FIXME: Pass the region. + computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, nullptr); // FIXME: Pass the region. /*-----------------------------------------------------------------------*\ * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left' @@ -3939,10 +4229,10 @@ void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValue // positioned, inline containing block because right now, it is using the logical left position // of the first line box when really it should use the last line box. When // this is fixed elsewhere, this block should be removed. - if (containerBlock->isRenderInline() && !containerBlock->style().isLeftToRightDirection()) { - const RenderInline* flow = toRenderInline(containerBlock); - InlineFlowBox* firstLine = flow->firstLineBox(); - InlineFlowBox* lastLine = flow->lastLineBox(); + if (is<RenderInline>(containerBlock) && !containerBlock.style().isLeftToRightDirection()) { + const auto& flow = downcast<RenderInline>(containerBlock); + InlineFlowBox* firstLine = flow.firstLineBox(); + InlineFlowBox* lastLine = flow.lastLineBox(); if (firstLine && lastLine && firstLine != lastLine) { computedValues.m_position = logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft()); return; @@ -3963,10 +4253,10 @@ void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValu // the numbers correspond to numbers in spec) // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline. - const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container()); + const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container()); const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock); - const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false); + const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false); // Variables to solve. Length marginBefore = style().marginBefore(); @@ -4083,7 +4373,7 @@ void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValu computedValues.m_position = logicalTopPos; } -LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine) +LayoutRect RenderBox::localCaretRect(InlineBox* box, unsigned caretOffset, LayoutUnit* extraWidthToEndOfLine) { // VisiblePositions at offsets inside containers either a) refer to the positions before/after // those containers (tables and select elements) or b) refer to the position inside an empty block. @@ -4124,7 +4414,7 @@ LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit // FIXME: Border/padding should be added for all elements but this workaround // is needed because we use offsets inside an "atomic" element to represent // positions before and after the element in deprecated editing offsets. - if (element() && !(editingIgnoresContent(element()) || isTableElement(element()))) { + if (element() && !(editingIgnoresContent(*element()) || isRenderedTable(element()))) { rect.setX(rect.x() + borderLeft() + paddingLeft()); rect.setY(rect.y() + paddingTop() + borderTop()); } @@ -4135,15 +4425,15 @@ LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit return rect; } -VisiblePosition RenderBox::positionForPoint(const LayoutPoint& point) +VisiblePosition RenderBox::positionForPoint(const LayoutPoint& point, const RenderRegion* region) { // no children...return this render object's element, if there is one, and offset 0 if (!firstChild()) return createVisiblePosition(nonPseudoElement() ? firstPositionInOrBeforeNode(nonPseudoElement()) : Position()); if (isTable() && nonPseudoElement()) { - LayoutUnit right = contentWidth() + borderAndPaddingWidth(); - LayoutUnit bottom = contentHeight() + borderAndPaddingHeight(); + LayoutUnit right = contentWidth() + horizontalBorderAndPaddingExtent(); + LayoutUnit bottom = contentHeight() + verticalBorderAndPaddingExtent(); if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) { if (point.x() <= right / 2) @@ -4154,29 +4444,31 @@ VisiblePosition RenderBox::positionForPoint(const LayoutPoint& point) // Pass off to the closest child. LayoutUnit minDist = LayoutUnit::max(); - RenderBox* closestRenderer = 0; + RenderBox* closestRenderer = nullptr; LayoutPoint adjustedPoint = point; if (isTableRow()) adjustedPoint.moveBy(location()); - for (RenderObject* renderObject = firstChild(); renderObject; renderObject = renderObject->nextSibling()) { - if (!renderObject->isBox()) - continue; - RenderBox* renderer = toRenderBox(renderObject); + for (auto& renderer : childrenOfType<RenderBox>(*this)) { + if (is<RenderFlowThread>(*this)) { + ASSERT(region); + if (!downcast<RenderFlowThread>(*this).objectShouldFragmentInFlowRegion(&renderer, region)) + continue; + } - if ((!renderer->firstChild() && !renderer->isInline() && !renderer->isRenderBlockFlow() ) - || renderer->style().visibility() != VISIBLE) + if ((!renderer.firstChild() && !renderer.isInline() && !is<RenderBlockFlow>(renderer)) + || renderer.style().visibility() != VISIBLE) continue; - LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? LayoutUnit() : renderer->y()); - LayoutUnit bottom = top + renderer->contentHeight(); - LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? LayoutUnit() : renderer->x()); - LayoutUnit right = left + renderer->contentWidth(); + LayoutUnit top = renderer.borderTop() + renderer.paddingTop() + (is<RenderTableRow>(*this) ? LayoutUnit() : renderer.y()); + LayoutUnit bottom = top + renderer.contentHeight(); + LayoutUnit left = renderer.borderLeft() + renderer.paddingLeft() + (is<RenderTableRow>(*this) ? LayoutUnit() : renderer.x()); + LayoutUnit right = left + renderer.contentWidth(); if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) { - if (renderer->isTableRow()) - return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset()); - return renderer->positionForPoint(point - renderer->locationOffset()); + if (is<RenderTableRow>(renderer)) + return renderer.positionForPoint(point + adjustedPoint - renderer.locationOffset(), region); + return renderer.positionForPoint(point - renderer.locationOffset(), region); } // Find the distance from (x, y) to the box. Split the space around the box into 8 pieces @@ -4207,13 +4499,13 @@ VisiblePosition RenderBox::positionForPoint(const LayoutPoint& point) LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height(); if (dist < minDist) { - closestRenderer = renderer; + closestRenderer = &renderer; minDist = dist; } } if (closestRenderer) - return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset()); + return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset(), region); return createVisiblePosition(firstPositionInOrBeforeNode(nonPseudoElement())); } @@ -4228,18 +4520,24 @@ bool RenderBox::shrinkToAvoidFloats() const return style().width().isAuto(); } +bool RenderBox::createsNewFormattingContext() const +{ + return (isInlineBlockOrInlineTable() && !isAnonymousInlineBlock()) || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || isFlexItemIncludingDeprecated() + || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isDocumentElementRenderer() || isRenderFlowThread() || isRenderRegion() + || isGridItem() || style().specifiesColumns() || style().columnSpan(); +} + bool RenderBox::avoidsFloats() const { - return isReplaced() || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isFlexItemIncludingDeprecated(); + return (isReplaced() && !isAnonymousInlineBlock()) || isHR() || isLegend() || createsNewFormattingContext(); } void RenderBox::addVisualEffectOverflow() { - if (!style().boxShadow() && !style().hasBorderImageOutsets()) + if (!style().boxShadow() && !style().hasBorderImageOutsets() && !outlineStyleForRepaint().hasOutlineInVisualOverflow()) return; - LayoutRect borderBox = borderBoxRect(); - addVisualOverflow(applyVisualEffectOverflow(borderBox)); + addVisualOverflow(applyVisualEffectOverflow(borderBoxRect())); RenderFlowThread* flowThread = flowThreadContainingBlock(); if (flowThread) @@ -4283,11 +4581,18 @@ LayoutRect RenderBox::applyVisualEffectOverflow(const LayoutRect& borderBox) con overflowMaxY = std::max(overflowMaxY, borderBox.maxY() + ((!isFlipped || !isHorizontal) ? borderOutsets.bottom() : borderOutsets.top())); } + if (outlineStyleForRepaint().hasOutlineInVisualOverflow()) { + LayoutUnit outlineSize = outlineStyleForRepaint().outlineSize(); + overflowMinX = std::min(overflowMinX, borderBox.x() - outlineSize); + overflowMaxX = std::max(overflowMaxX, borderBox.maxX() + outlineSize); + overflowMinY = std::min(overflowMinY, borderBox.y() - outlineSize); + overflowMaxY = std::max(overflowMaxY, borderBox.maxY() + outlineSize); + } // Add in the final overflow with shadows and outsets combined. return LayoutRect(overflowMinX, overflowMinY, overflowMaxX - overflowMinX, overflowMaxY - overflowMinY); } -void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta) +void RenderBox::addOverflowFromChild(const RenderBox* child, const LayoutSize& delta) { // Never allow flow threads to propagate overflow up to a parent. if (child->isRenderFlowThread()) @@ -4316,7 +4621,7 @@ void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta) void RenderBox::addLayoutOverflow(const LayoutRect& rect) { - LayoutRect clientBox = clientBoxRect(); + LayoutRect clientBox = flippedClientBoxRect(); if (clientBox.contains(rect) || rect.isEmpty()) return; @@ -4357,36 +4662,69 @@ void RenderBox::addVisualOverflow(const LayoutRect& rect) return; if (!m_overflow) - m_overflow = adoptRef(new RenderOverflow(clientBoxRect(), borderBox)); + m_overflow = adoptRef(new RenderOverflow(flippedClientBoxRect(), borderBox)); m_overflow->addVisualOverflow(rect); } void RenderBox::clearOverflow() { - m_overflow.clear(); + m_overflow = nullptr; RenderFlowThread* flowThread = flowThreadContainingBlock(); if (flowThread) flowThread->clearRegionsOverflow(this); } -inline static bool percentageLogicalHeightIsResolvable(const RenderBox* box) +static bool logicalWidthIsResolvable(const RenderBox& renderBox) +{ + const RenderBox* box = &renderBox; + while (box && !is<RenderView>(*box) && !box->isOutOfFlowPositioned() + && !box->hasOverrideContainingBlockLogicalWidth() + && (box->style().logicalWidth().isAuto() || box->isAnonymousBlock())) + box = box->containingBlock(); + + if (box->style().logicalWidth().isFixed()) + return true; + if (box->isRenderView()) + return true; + // The size of the containing block of an absolutely positioned element is always definite with respect to that + // element (http://dev.w3.org/csswg/css-sizing-3/#definite). + if (box->isOutOfFlowPositioned()) + return true; + if (box->hasOverrideContainingBlockLogicalWidth()) + return static_cast<bool>(box->overrideContainingBlockContentLogicalWidth()); + if (box->style().logicalWidth().isPercentOrCalculated()) + return logicalWidthIsResolvable(*box->containingBlock()); + + return false; +} + +bool RenderBox::hasDefiniteLogicalWidth() const +{ + return logicalWidthIsResolvable(*this); +} + +inline static bool percentageLogicalHeightIsResolvable(const RenderBox& box) { - return RenderBox::percentageLogicalHeightIsResolvableFromBlock(box->containingBlock(), box->isOutOfFlowPositioned()); + return RenderBox::percentageLogicalHeightIsResolvableFromBlock(*box.containingBlock(), box.isOutOfFlowPositioned(), box.scrollsOverflowY()); } -bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* containingBlock, bool isOutOfFlowPositioned) +bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock& containingBlock, bool isOutOfFlowPositioned, bool scrollsOverflowY) { // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing // block that may have a specified height and then use it. In strict mode, this violates the // specification, which states that percentage heights just revert to auto if the containing // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look // only at explicit containers. - const RenderBlock* cb = containingBlock; + const RenderBlock* cb = &containingBlock; bool inQuirksMode = cb->document().inQuirksMode(); - while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style().logicalHeight().isAuto()) { + bool skippedAutoHeightContainingBlock = false; + while (cb && !is<RenderView>(*cb) && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style().logicalHeight().isAuto()) { if (!inQuirksMode && !cb->isAnonymousBlock()) break; + if (cb->hasOverrideContainingBlockLogicalHeight()) + return static_cast<bool>(cb->overrideContainingBlockContentLogicalHeight()); + skippedAutoHeightContainingBlock = true; cb = cb->containingBlock(); } @@ -4399,18 +4737,20 @@ bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* // Table cells violate what the CSS spec says to do with heights. Basically we // don't care if the cell specified a height or not. We just always make ourselves // be a percentage of the cell's current content height. - if (cb->isTableCell()) - return true; + if (cb->isTableCell()) { + // Matches computePercentageLogicalHeight(). + return skippedAutoHeightContainingBlock || cb->hasOverrideLogicalContentHeight() || tableCellShouldHaveZeroInitialSize(*cb, scrollsOverflowY); + } // Otherwise we only use our percentage height if our containing block had a specified // height. if (cb->style().logicalHeight().isFixed()) return true; - if (cb->style().logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) - return percentageLogicalHeightIsResolvableFromBlock(cb->containingBlock(), cb->isOutOfFlowPositioned()); + if (cb->style().logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) + return percentageLogicalHeightIsResolvableFromBlock(*cb->containingBlock(), cb->isOutOfFlowPositioned(), cb->scrollsOverflowY()); if (cb->isRenderView() || inQuirksMode || isOutOfFlowPositionedWithSpecifiedHeight) return true; - if (cb->isRoot() && isOutOfFlowPositioned) { + if (cb->isDocumentElementRenderer() && isOutOfFlowPositioned) { // Match the positioned objects behavior, which is that positioned objects will fill their viewport // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block. return true; @@ -4419,6 +4759,23 @@ bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* return false; } +bool RenderBox::hasDefiniteLogicalHeight() const +{ + const Length& logicalHeight = style().logicalHeight(); + if (logicalHeight.isFixed()) + return true; + // The size of the containing block of an absolutely positioned element is always definite with respect to that + // element (http://dev.w3.org/csswg/css-sizing-3/#definite). + if (isOutOfFlowPositioned()) + return true; + if (hasOverrideContainingBlockLogicalHeight()) + return static_cast<bool>(overrideContainingBlockContentLogicalHeight()); + if (logicalHeight.isIntrinsicOrAuto()) + return false; + + return percentageLogicalHeightIsResolvable(*this); +} + bool RenderBox::hasUnsplittableScrollingOverflow() const { // We will paginate as long as we don't scroll overflow in the pagination direction. @@ -4432,16 +4789,17 @@ bool RenderBox::hasUnsplittableScrollingOverflow() const // conditions, but it should work out to be good enough for common cases. Paginating overflow // with scrollbars present is not the end of the world and is what we used to do in the old model anyway. return !style().logicalHeight().isIntrinsicOrAuto() - || (!style().logicalMaxHeight().isIntrinsicOrAuto() && !style().logicalMaxHeight().isUndefined() && (!style().logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this))) - || (!style().logicalMinHeight().isIntrinsicOrAuto() && style().logicalMinHeight().isPositive() && (!style().logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this))); + || (!style().logicalMaxHeight().isIntrinsicOrAuto() && !style().logicalMaxHeight().isUndefined() && (!style().logicalMaxHeight().isPercentOrCalculated() || percentageLogicalHeightIsResolvable(*this))) + || (!style().logicalMinHeight().isIntrinsicOrAuto() && style().logicalMinHeight().isPositive() && (!style().logicalMinHeight().isPercentOrCalculated() || percentageLogicalHeightIsResolvable(*this))); } bool RenderBox::isUnsplittableForPagination() const { - return isReplaced() || hasUnsplittableScrollingOverflow() || (parent() && isWritingModeRoot()) - // FIXME: Treat multi-column elements as unsplittable for now. Remove once we implement the correct - // fragmentation model for multicolumn. - || isMultiColumnBlockFlow(); + return isReplaced() + || hasUnsplittableScrollingOverflow() + || (parent() && isWritingModeRoot()) + || isRenderNamedFlowFragmentContainer() + || fixedPositionedWithNamedFlowContainingBlock(); } LayoutUnit RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const @@ -4472,7 +4830,7 @@ RenderLayer* RenderBox::enclosingFloatPaintingLayer() const return nullptr; } -LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const +LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(const RenderStyle* parentStyle) const { LayoutRect rect = visualOverflowRectForPropagation(parentStyle); if (!parentStyle->isHorizontalWritingMode()) @@ -4480,7 +4838,7 @@ LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* paren return rect; } -LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const +LayoutRect RenderBox::visualOverflowRectForPropagation(const RenderStyle* parentStyle) const { // If the writing modes of the child and parent match, then we don't have to // do anything fancy. Just return the result. @@ -4498,7 +4856,7 @@ LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) return rect; } -LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const +LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(const RenderStyle* parentStyle) const { LayoutRect rect = layoutOverflowRectForPropagation(parentStyle); if (!parentStyle->isHorizontalWritingMode()) @@ -4506,16 +4864,16 @@ LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* paren return rect; } -LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const +LayoutRect RenderBox::layoutOverflowRectForPropagation(const RenderStyle* parentStyle) const { // Only propagate interior layout overflow if we don't clip it. LayoutRect rect = borderBoxRect(); if (!hasOverflowClip()) rect.unite(layoutOverflowRect()); - bool hasTransform = hasLayer() && layer()->transform(); + bool hasTransform = this->hasTransform(); #if PLATFORM(IOS) - if (isInFlowPositioned() || (hasTransform && document().settings()->shouldTransformsAffectOverflow())) { + if (isInFlowPositioned() || (hasTransform && settings().shouldTransformsAffectOverflow())) { #else if (isInFlowPositioned() || hasTransform) { #endif @@ -4549,7 +4907,29 @@ LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) return rect; } -LayoutRect RenderBox::overflowRectForPaintRejection(RenderRegion* region) const +LayoutRect RenderBox::flippedClientBoxRect() const +{ + // Because of the special coordinate system used for overflow rectangles (not quite logical, not + // quite physical), we need to flip the block progression coordinate in vertical-rl and + // horizontal-bt writing modes. Apart from that, this method does the same as clientBoxRect(). + + LayoutUnit left = borderLeft(); + LayoutUnit top = borderTop(); + LayoutUnit right = borderRight(); + LayoutUnit bottom = borderBottom(); + // Calculate physical padding box. + LayoutRect rect(left, top, width() - left - right, height() - top - bottom); + // Flip block progression axis if writing mode is vertical-rl or horizontal-bt. + flipForWritingMode(rect); + // Subtract space occupied by scrollbars. They are at their physical edge in this coordinate + // system, so order is important here: first flip, then subtract scrollbars. + if (shouldPlaceBlockDirectionScrollbarOnLeft()) + rect.move(verticalScrollbarWidth(), 0); + rect.contract(verticalScrollbarWidth(), horizontalScrollbarHeight()); + return rect; +} + +LayoutRect RenderBox::overflowRectForPaintRejection(RenderNamedFlowFragment* namedFlowFragment) const { LayoutRect overflowRect = visualOverflowRect(); @@ -4557,22 +4937,19 @@ LayoutRect RenderBox::overflowRectForPaintRejection(RenderRegion* region) const // cause the paint rejection algorithm to prevent them from painting when using different width regions. // e.g. an absolutely positioned box with bottom:0px and right:0px would have it's frameRect.x relative // to the flow thread, not the last region (in which it will end up because of bottom:0px) - if (region) { - if (RenderFlowThread* flowThread = region->flowThread()) { - RenderRegion* startRegion = 0; - RenderRegion* endRegion = 0; - flowThread->getRegionRangeForBox(this, startRegion, endRegion); - - if (startRegion && endRegion) - overflowRect.unite(region->visualOverflowRectForBox(this)); - } + if (namedFlowFragment && namedFlowFragment->isValid()) { + RenderFlowThread* flowThread = namedFlowFragment->flowThread(); + RenderRegion* startRegion = nullptr; + RenderRegion* endRegion = nullptr; + if (flowThread->getRegionRangeForBox(this, startRegion, endRegion)) + overflowRect.unite(namedFlowFragment->visualOverflowRectForBox(*this)); } if (!m_overflow || !usesCompositedScrolling()) return overflowRect; overflowRect.unite(layoutOverflowRect()); - overflowRect.move(-scrolledContentOffset()); + overflowRect.moveBy(-scrollPosition()); return overflowRect; } @@ -4623,13 +5000,6 @@ LayoutPoint RenderBox::flipForWritingMode(const LayoutPoint& position) const return isHorizontalWritingMode() ? LayoutPoint(position.x(), height() - position.y()) : LayoutPoint(width() - position.x(), position.y()); } -LayoutPoint RenderBox::flipForWritingModeIncludingColumns(const LayoutPoint& point) const -{ - if (!hasColumns() || !style().isFlippedBlocksWritingMode()) - return flipForWritingMode(point); - return toRenderBlock(this)->flipForWritingModeIncludingColumns(point); -} - LayoutSize RenderBox::flipForWritingMode(const LayoutSize& offset) const { if (!style().isFlippedBlocksWritingMode()) @@ -4657,6 +5027,9 @@ void RenderBox::flipForWritingMode(FloatRect& rect) const LayoutPoint RenderBox::topLeftLocation() const { + if (!view().frameView().hasFlippedBlockRenderers()) + return location(); + RenderBlock* containerBlock = containingBlock(); if (!containerBlock || containerBlock == this) return location(); @@ -4665,6 +5038,9 @@ LayoutPoint RenderBox::topLeftLocation() const LayoutSize RenderBox::topLeftLocationOffset() const { + if (!view().frameView().hasFlippedBlockRenderers()) + return locationOffset(); + RenderBlock* containerBlock = containingBlock(); if (!containerBlock || containerBlock == this) return locationOffset(); @@ -4674,39 +5050,52 @@ LayoutSize RenderBox::topLeftLocationOffset() const return LayoutSize(rect.x(), rect.y()); } +void RenderBox::applyTopLeftLocationOffsetWithFlipping(LayoutPoint& point) const +{ + RenderBlock* containerBlock = containingBlock(); + if (!containerBlock || containerBlock == this) { + point.move(m_frameRect.x(), m_frameRect.y()); + return; + } + + LayoutRect rect(frameRect()); + containerBlock->flipForWritingMode(rect); // FIXME: This is wrong if we are an absolutely positioned object enclosed by a relative-positioned inline. + point.move(rect.x(), rect.y()); +} + bool RenderBox::hasRelativeDimensions() const { - return style().height().isPercent() || style().width().isPercent() - || style().maxHeight().isPercent() || style().maxWidth().isPercent() - || style().minHeight().isPercent() || style().minWidth().isPercent(); + return style().height().isPercentOrCalculated() || style().width().isPercentOrCalculated() + || style().maxHeight().isPercentOrCalculated() || style().maxWidth().isPercentOrCalculated() + || style().minHeight().isPercentOrCalculated() || style().minWidth().isPercentOrCalculated(); } bool RenderBox::hasRelativeLogicalHeight() const { - return style().logicalHeight().isPercent() - || style().logicalMinHeight().isPercent() - || style().logicalMaxHeight().isPercent(); + return style().logicalHeight().isPercentOrCalculated() + || style().logicalMinHeight().isPercentOrCalculated() + || style().logicalMaxHeight().isPercentOrCalculated(); } -bool RenderBox::hasViewportPercentageLogicalHeight() const +bool RenderBox::hasRelativeLogicalWidth() const { - return style().logicalHeight().isViewportPercentage() - || style().logicalMinHeight().isViewportPercentage() - || style().logicalMaxHeight().isViewportPercentage(); + return style().logicalWidth().isPercentOrCalculated() + || style().logicalMinWidth().isPercentOrCalculated() + || style().logicalMaxWidth().isPercentOrCalculated(); } -static void markBoxForRelayoutAfterSplit(RenderBox* box) +static void markBoxForRelayoutAfterSplit(RenderBox& box) { // FIXME: The table code should handle that automatically. If not, // we should fix it and remove the table part checks. - if (box->isTable()) { + if (is<RenderTable>(box)) { // Because we may have added some sections with already computed column structures, we need to // sync the table structure with them now. This avoids crashes when adding new cells to the table. - toRenderTable(box)->forceSectionsRecalc(); - } else if (box->isTableSection()) - toRenderTableSection(box)->setNeedsCellRecalc(); + downcast<RenderTable>(box).forceSectionsRecalc(); + } else if (is<RenderTableSection>(box)) + downcast<RenderTableSection>(box).setNeedsCellRecalc(); - box->setNeedsLayoutAndPrefWidthsRecalc(); + box.setNeedsLayoutAndPrefWidthsRecalc(); } RenderObject* RenderBox::splitAnonymousBoxesAroundChild(RenderObject* beforeChild) @@ -4714,32 +5103,32 @@ RenderObject* RenderBox::splitAnonymousBoxesAroundChild(RenderObject* beforeChil bool didSplitParentAnonymousBoxes = false; while (beforeChild->parent() != this) { - RenderBox* boxToSplit = toRenderBox(beforeChild->parent()); - if (boxToSplit->firstChild() != beforeChild && boxToSplit->isAnonymous()) { + auto& boxToSplit = downcast<RenderBox>(*beforeChild->parent()); + if (boxToSplit.firstChild() != beforeChild && boxToSplit.isAnonymous()) { didSplitParentAnonymousBoxes = true; // We have to split the parent box into two boxes and move children // from |beforeChild| to end into the new post box. - RenderBox* postBox = boxToSplit->createAnonymousBoxWithSameTypeAs(this); - postBox->setChildrenInline(boxToSplit->childrenInline()); - RenderBox* parentBox = toRenderBox(boxToSplit->parent()); + auto* postBox = boxToSplit.createAnonymousBoxWithSameTypeAs(*this).release(); + postBox->setChildrenInline(boxToSplit.childrenInline()); + RenderBox* parentBox = downcast<RenderBox>(boxToSplit.parent()); // We need to invalidate the |parentBox| before inserting the new node // so that the table repainting logic knows the structure is dirty. // See for example RenderTableCell:clippedOverflowRectForRepaint. - markBoxForRelayoutAfterSplit(parentBox); - parentBox->insertChildInternal(postBox, boxToSplit->nextSibling(), NotifyChildren); - boxToSplit->moveChildrenTo(postBox, beforeChild, 0, true); + markBoxForRelayoutAfterSplit(*parentBox); + parentBox->insertChildInternal(postBox, boxToSplit.nextSibling(), NotifyChildren); + boxToSplit.moveChildrenTo(postBox, beforeChild, nullptr, true); markBoxForRelayoutAfterSplit(boxToSplit); - markBoxForRelayoutAfterSplit(postBox); + markBoxForRelayoutAfterSplit(*postBox); beforeChild = postBox; } else - beforeChild = boxToSplit; + beforeChild = &boxToSplit; } if (didSplitParentAnonymousBoxes) - markBoxForRelayoutAfterSplit(this); + markBoxForRelayoutAfterSplit(*this); ASSERT(beforeChild->parent() == this); return beforeChild; @@ -4755,4 +5144,17 @@ LayoutUnit RenderBox::offsetFromLogicalTopOfFirstPage() const return containerBlock->offsetFromLogicalTopOfFirstPage() + logicalTop(); } +const RenderBox* RenderBox::findEnclosingScrollableContainer() const +{ + for (auto& candidate : lineageOfType<RenderBox>(*this)) { + if (candidate.hasOverflowClip()) + return &candidate; + } + // If all parent elements are not overflow scrollable, check the body. + if (document().body() && frame().mainFrame().view() && frame().mainFrame().view()->isScrollable()) + return document().body()->renderBox(); + + return nullptr; +} + } // namespace WebCore |