2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5 * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013, 2015 Apple Inc. All rights reserved.
7 * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
26 #include "RenderElement.h"
28 #include "AXObjectCache.h"
29 #include "ContentData.h"
30 #include "ControlStates.h"
31 #include "CursorList.h"
32 #include "ElementChildIterator.h"
33 #include "EventHandler.h"
35 #include "FrameSelection.h"
36 #include "HTMLBodyElement.h"
37 #include "HTMLHtmlElement.h"
38 #include "HTMLNames.h"
39 #include "FlowThreadController.h"
40 #include "RenderBlock.h"
41 #include "RenderCounter.h"
42 #include "RenderDeprecatedFlexibleBox.h"
43 #include "RenderFlexibleBox.h"
44 #include "RenderImage.h"
45 #include "RenderImageResourceStyleImage.h"
46 #include "RenderInline.h"
47 #include "RenderIterator.h"
48 #include "RenderLayer.h"
49 #include "RenderLayerCompositor.h"
50 #include "RenderLineBreak.h"
51 #include "RenderListItem.h"
52 #include "RenderNamedFlowThread.h"
53 #include "RenderRegion.h"
54 #include "RenderTableCaption.h"
55 #include "RenderTableCell.h"
56 #include "RenderTableCol.h"
57 #include "RenderTableRow.h"
58 #include "RenderText.h"
59 #include "RenderTheme.h"
60 #include "RenderView.h"
61 #include "SVGRenderSupport.h"
63 #include "ShadowRoot.h"
64 #include "StyleResolver.h"
65 #include <wtf/MathExtras.h>
66 #include <wtf/StackStats.h>
68 #if ENABLE(CSS_GRID_LAYOUT)
69 #include "RenderGrid.h"
74 bool RenderElement::s_affectsParentBlock = false;
75 bool RenderElement::s_noLongerAffectsParentBlock = false;
77 static HashMap<const RenderObject*, ControlStates*>& controlStatesRendererMap()
79 static NeverDestroyed<HashMap<const RenderObject*, ControlStates*>> map;
83 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
84 : RenderObject(elementOrDocument)
85 , m_baseTypeFlags(baseTypeFlags)
86 , m_ancestorLineBoxDirty(false)
87 , m_hasInitializedStyle(false)
88 , m_renderInlineAlwaysCreatesLineBoxes(false)
89 , m_renderBoxNeedsLazyRepaint(false)
90 , m_hasPausedImageAnimations(false)
91 , m_hasCounterNodeMap(false)
92 , m_isCSSAnimating(false)
93 , m_hasContinuation(false)
94 , m_renderBlockHasMarginBeforeQuirk(false)
95 , m_renderBlockHasMarginAfterQuirk(false)
96 , m_renderBlockHasBorderOrPaddingLogicalWidthChanged(false)
97 , m_renderBlockFlowHasMarkupTruncation(false)
98 , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
99 , m_firstChild(nullptr)
100 , m_lastChild(nullptr)
101 , m_style(WTF::move(style))
105 RenderElement::RenderElement(Element& element, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
106 : RenderElement(static_cast<ContainerNode&>(element), WTF::move(style), baseTypeFlags)
110 RenderElement::RenderElement(Document& document, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
111 : RenderElement(static_cast<ContainerNode&>(document), WTF::move(style), baseTypeFlags)
115 RenderElement::~RenderElement()
117 if (hasInitializedStyle()) {
118 for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
119 if (StyleImage* backgroundImage = bgLayer->image())
120 backgroundImage->removeClient(this);
123 for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
124 if (StyleImage* maskImage = maskLayer->image())
125 maskImage->removeClient(this);
126 else if (maskLayer->maskImage().get())
127 maskLayer->maskImage()->removeRendererImageClient(this);
130 if (StyleImage* borderImage = m_style->borderImage().image())
131 borderImage->removeClient(this);
133 if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
134 maskBoxImage->removeClient(this);
136 #if ENABLE(CSS_SHAPES)
137 if (auto shapeValue = m_style->shapeOutside()) {
138 if (auto shapeImage = shapeValue->image())
139 shapeImage->removeClient(this);
143 if (m_hasPausedImageAnimations)
144 view().removeRendererWithPausedImageAnimations(*this);
147 RenderPtr<RenderElement> RenderElement::createFor(Element& element, Ref<RenderStyle>&& style)
149 // Minimal support for content properties replacing an entire element.
150 // Works only if we have exactly one piece of content and it's a URL.
151 // Otherwise acts as if we didn't support this feature.
152 const ContentData* contentData = style.get().contentData();
153 if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
154 auto& styleImage = downcast<ImageContentData>(*contentData).image();
155 auto image = createRenderer<RenderImage>(element, WTF::move(style), const_cast<StyleImage*>(&styleImage));
156 image->setIsGeneratedContent();
157 return WTF::move(image);
160 switch (style.get().display()) {
164 return createRenderer<RenderInline>(element, WTF::move(style));
168 return createRenderer<RenderBlockFlow>(element, WTF::move(style));
170 return createRenderer<RenderListItem>(element, WTF::move(style));
173 return createRenderer<RenderTable>(element, WTF::move(style));
174 case TABLE_ROW_GROUP:
175 case TABLE_HEADER_GROUP:
176 case TABLE_FOOTER_GROUP:
177 return createRenderer<RenderTableSection>(element, WTF::move(style));
179 return createRenderer<RenderTableRow>(element, WTF::move(style));
180 case TABLE_COLUMN_GROUP:
182 return createRenderer<RenderTableCol>(element, WTF::move(style));
184 return createRenderer<RenderTableCell>(element, WTF::move(style));
186 return createRenderer<RenderTableCaption>(element, WTF::move(style));
189 return createRenderer<RenderDeprecatedFlexibleBox>(element, WTF::move(style));
193 case WEBKIT_INLINE_FLEX:
194 return createRenderer<RenderFlexibleBox>(element, WTF::move(style));
195 #if ENABLE(CSS_GRID_LAYOUT)
198 return createRenderer<RenderGrid>(element, WTF::move(style));
201 ASSERT_NOT_REACHED();
205 enum StyleCacheState {
210 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderElement& renderer, RenderStyle* style)
212 RenderElement& rendererForFirstLineStyle = renderer.isBeforeOrAfterContent() ? *renderer.parent() : const_cast<RenderElement&>(renderer);
214 if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
215 if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock()) {
217 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
218 return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == &renderer ? style : nullptr);
220 } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
221 RenderStyle& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
222 if (&parentStyle != &rendererForFirstLineStyle.parent()->style()) {
223 if (type == Cached) {
224 // A first-line style is in effect. Cache a first-line style for ourselves.
225 rendererForFirstLineStyle.style().setHasPseudoStyle(FIRST_LINE_INHERITED);
226 return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, &parentStyle);
228 return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
234 PassRefPtr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
236 if (!document().styleSheetCollection().usesFirstLineRules())
239 return firstLineStyleForCachedUncachedType(Uncached, *this, style);
242 RenderStyle* RenderElement::cachedFirstLineStyle() const
244 ASSERT(document().styleSheetCollection().usesFirstLineRules());
246 RenderStyle& style = this->style();
247 if (RefPtr<RenderStyle> firstLineStyle = firstLineStyleForCachedUncachedType(Cached, *this, &style))
248 return firstLineStyle.get();
253 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
255 // If transform changed, and we are not composited, need to do a layout.
256 if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
257 // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
258 if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
260 diff = std::max(diff, StyleDifferenceLayout);
262 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
263 // then we actually need SimplifiedLayoutAndPositionedMovement.
264 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
268 diff = std::max(diff, StyleDifferenceRecompositeLayer);
271 if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
272 if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
273 diff = std::max(diff, StyleDifferenceRepaintLayer);
275 diff = std::max(diff, StyleDifferenceRecompositeLayer);
278 if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
280 && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
282 && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
283 diff = std::max(diff, StyleDifferenceRecompositeLayer);
285 diff = std::max(diff, StyleDifferenceRepaint);
288 if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
289 RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
290 if (!layer->isComposited() || layer->paintsWithFilters())
291 diff = std::max(diff, StyleDifferenceRepaintLayer);
293 diff = std::max(diff, StyleDifferenceRecompositeLayer);
296 // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
297 // style changing, since it depends on whether we decide to composite these elements. When the
298 // layer status of one of these elements changes, we need to force a layout.
299 if (diff < StyleDifferenceLayout && isRenderLayerModelObject()) {
300 if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
301 diff = StyleDifferenceLayout;
304 // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
305 if (diff == StyleDifferenceRepaintLayer && !hasLayer())
306 diff = StyleDifferenceRepaint;
311 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
313 for (auto& child : childrenOfType<RenderObject>(*this)) {
314 if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
316 if (child.style().hasOutline() || child.style().hasBorder())
322 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
324 return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
327 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
329 // Optimize the common case
330 if (FillLayer::imagesIdentical(oldLayers, newLayers))
333 // Go through the new layers and addClients first, to avoid removing all clients of an image.
334 for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
335 if (StyleImage* image = currNew->image())
336 image->addClient(this);
337 else if (currNew->maskImage().get())
338 currNew->maskImage()->addRendererImageClient(this);
341 for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
342 if (StyleImage* image = currOld->image())
343 image->removeClient(this);
344 else if (currOld->maskImage().get())
345 currOld->maskImage()->removeRendererImageClient(this);
349 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
351 if (oldImage == newImage)
354 oldImage->removeClient(this);
356 newImage->addClient(this);
359 #if ENABLE(CSS_SHAPES)
360 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
362 if (oldShapeValue || newShapeValue)
363 updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
367 void RenderElement::initializeStyle()
369 styleWillChange(StyleDifferenceNewStyle, style());
371 m_hasInitializedStyle = true;
373 updateFillImages(nullptr, m_style->backgroundLayers());
374 updateFillImages(nullptr, m_style->maskLayers());
376 updateImage(nullptr, m_style->borderImage().image());
377 updateImage(nullptr, m_style->maskBoxImage().image());
379 #if ENABLE(CSS_SHAPES)
380 updateShapeImage(nullptr, m_style->shapeOutside());
383 // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
384 // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
385 if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
386 view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
388 styleDidChange(StyleDifferenceNewStyle, nullptr);
390 // We shouldn't have any text children that would need styleDidChange at this point.
391 ASSERT(!childrenOfType<RenderText>(*this).first());
393 // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
394 // have their parent set before getting a call to initializeStyle() :|
397 void RenderElement::setStyle(Ref<RenderStyle>&& style, StyleDifference minimalStyleDifference)
399 // FIXME: Should change RenderView so it can use initializeStyle too.
400 // If we do that, we can assert m_hasInitializedStyle unconditionally,
401 // and remove the check of m_hasInitializedStyle below too.
402 ASSERT(m_hasInitializedStyle || isRenderView());
404 if (m_style.ptr() == style.ptr() && minimalStyleDifference != StyleDifferenceEqual) {
405 // FIXME: Can we change things so we never hit this code path?
406 // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
407 // style sharing is disabled for them. That should ensure that we never hit this code path.
408 ASSERT(!isRenderIFrame());
409 ASSERT(!isEmbeddedObject());
414 StyleDifference diff = StyleDifferenceEqual;
415 unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
416 if (m_hasInitializedStyle)
417 diff = m_style->diff(style.get(), contextSensitiveProperties);
419 diff = std::max(diff, minimalStyleDifference);
421 diff = adjustStyleDifference(diff, contextSensitiveProperties);
423 styleWillChange(diff, style.get());
425 Ref<RenderStyle> oldStyle(m_style.replace(WTF::move(style)));
427 updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
428 updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
430 updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
431 updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
433 #if ENABLE(CSS_SHAPES)
434 updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
437 // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
438 // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
439 if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
440 view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
442 bool doesNotNeedLayout = !parent();
444 styleDidChange(diff, oldStyle.ptr());
446 // Text renderers use their parent style. Notify them about the change.
447 for (auto& child : childrenOfType<RenderText>(*this))
448 child.styleDidChange(diff, oldStyle.ptr());
450 // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
451 // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
452 // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
453 // in the future as we move renderer changes out of layout and into style changes.
454 if (doesNotNeedLayout)
457 // Now that the layer (if any) has been updated, we need to adjust the diff again,
458 // check whether we should layout now, and decide if we need to repaint.
459 StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
461 if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
462 if (updatedDiff == StyleDifferenceLayout)
463 setNeedsLayoutAndPrefWidthsRecalc();
464 else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
465 setNeedsPositionedMovementLayout(oldStyle.ptr());
466 else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
467 setNeedsPositionedMovementLayout(oldStyle.ptr());
468 setNeedsSimplifiedNormalFlowLayout();
469 } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
470 setNeedsSimplifiedNormalFlowLayout();
473 if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
474 // Do a repaint with the new style now, e.g., for example if we go from
475 // not having an outline to having an outline.
480 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
482 bool needsTable = false;
484 if (is<RenderTableCol>(*newChild)) {
485 RenderTableCol& newTableColumn = downcast<RenderTableCol>(*newChild);
486 bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
487 needsTable = !is<RenderTable>(*this) && !isColumnInColumnGroup;
488 } else if (is<RenderTableCaption>(*newChild))
489 needsTable = !is<RenderTable>(*this);
490 else if (is<RenderTableSection>(*newChild))
491 needsTable = !is<RenderTable>(*this);
492 else if (is<RenderTableRow>(*newChild))
493 needsTable = !is<RenderTableSection>(*this);
494 else if (is<RenderTableCell>(*newChild))
495 needsTable = !is<RenderTableRow>(*this);
499 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
500 if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
501 table = downcast<RenderTable>(afterChild);
503 table = RenderTable::createAnonymousWithParentRenderer(this);
504 addChild(table, beforeChild);
506 table->addChild(newChild);
508 insertChildInternal(newChild, beforeChild, NotifyChildren);
510 if (is<RenderText>(*newChild))
511 downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
513 // SVG creates renderers for <g display="none">, as SVG requires children of hidden
514 // <g>s to have renderers - at least that's how our implementation works. Consider:
515 // <g display="none"><foreignObject><body style="position: relative">FOO...
516 // - requiresLayer() would return true for the <body>, creating a new RenderLayer
517 // - when the document is painted, both layers are painted. The <body> layer doesn't
518 // know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
519 // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
520 // and stop creating layers at all for these cases - they're not used anyways.
521 if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
522 downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
524 SVGRenderSupport::childAdded(*this, *newChild);
527 void RenderElement::removeChild(RenderObject& oldChild)
529 removeChildInternal(oldChild, NotifyChildren);
532 void RenderElement::destroyLeftoverChildren()
534 while (m_firstChild) {
535 if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
536 m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
538 // Destroy any anonymous children remaining in the render tree, as well as implicit (shadow) DOM elements like those used in the engine-based text fields.
539 if (m_firstChild->node())
540 m_firstChild->node()->setRenderer(nullptr);
541 m_firstChild->destroy();
546 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
548 ASSERT(canHaveChildren() || canHaveGeneratedChildren());
549 ASSERT(!newChild->parent());
550 ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
552 while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
553 beforeChild = beforeChild->parent();
555 // This should never happen, but if it does prevent render tree corruption
556 // where child->parent() ends up being owner but child->nextSibling()->parent()
558 if (beforeChild && beforeChild->parent() != this) {
559 ASSERT_NOT_REACHED();
563 newChild->setParent(this);
565 if (m_firstChild == beforeChild)
566 m_firstChild = newChild;
569 RenderObject* previousSibling = beforeChild->previousSibling();
571 previousSibling->setNextSibling(newChild);
572 newChild->setPreviousSibling(previousSibling);
573 newChild->setNextSibling(beforeChild);
574 beforeChild->setPreviousSibling(newChild);
577 lastChild()->setNextSibling(newChild);
578 newChild->setPreviousSibling(lastChild());
579 m_lastChild = newChild;
582 if (!documentBeingDestroyed()) {
583 if (notifyChildren == NotifyChildren)
584 newChild->insertedIntoTree();
585 if (is<RenderElement>(*newChild))
586 RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
589 newChild->setNeedsLayoutAndPrefWidthsRecalc();
590 setPreferredLogicalWidthsDirty(true);
591 if (!normalChildNeedsLayout())
592 setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
594 if (AXObjectCache* cache = document().axObjectCache())
595 cache->childrenChanged(this, newChild);
596 if (is<RenderBlockFlow>(*this))
597 downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
600 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
602 ASSERT(canHaveChildren() || canHaveGeneratedChildren());
603 ASSERT(oldChild.parent() == this);
605 if (oldChild.isFloatingOrOutOfFlowPositioned())
606 downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
608 // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
609 // that a positioned child got yanked). We also repaint, so that the area exposed when the child
610 // disappears gets repainted properly.
611 if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
612 oldChild.setNeedsLayoutAndPrefWidthsRecalc();
613 // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
614 if (oldChild.isBody())
615 view().repaintRootContents();
620 // If we have a line box wrapper, delete it.
621 if (is<RenderBox>(oldChild))
622 downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
623 else if (is<RenderLineBreak>(oldChild))
624 downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
626 // If oldChild is the start or end of the selection, then clear the selection to
627 // avoid problems of invalid pointers.
628 if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
629 frame().selection().setNeedsSelectionUpdate();
631 if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
632 oldChild.willBeRemovedFromTree();
634 // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
635 // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
636 // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
638 RenderObject* nextSibling = oldChild.nextSibling();
640 if (oldChild.previousSibling())
641 oldChild.previousSibling()->setNextSibling(nextSibling);
643 nextSibling->setPreviousSibling(oldChild.previousSibling());
645 if (m_firstChild == &oldChild)
646 m_firstChild = nextSibling;
647 if (m_lastChild == &oldChild)
648 m_lastChild = oldChild.previousSibling();
650 oldChild.setPreviousSibling(nullptr);
651 oldChild.setNextSibling(nullptr);
652 oldChild.setParent(nullptr);
654 // rendererRemovedFromTree walks the whole subtree. We can improve performance
655 // by skipping this step when destroying the entire tree.
656 if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
657 RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
659 if (AXObjectCache* cache = document().existingAXObjectCache())
660 cache->childrenChanged(this);
663 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
665 if (renderer.hasLayer()) {
666 if (!beforeChild && newObject) {
667 // We need to figure out the layer that follows newObject. We only do
668 // this the first time we find a child layer, and then we update the
669 // pointer values for newObject and beforeChild used by everyone else.
670 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
673 parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
677 for (auto& child : childrenOfType<RenderElement>(renderer))
678 addLayers(child, parentLayer, newObject, beforeChild);
681 void RenderElement::addLayers(RenderLayer* parentLayer)
686 RenderElement* renderer = this;
687 RenderLayer* beforeChild = nullptr;
688 WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
691 void RenderElement::removeLayers(RenderLayer* parentLayer)
697 parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
701 for (auto& child : childrenOfType<RenderElement>(*this))
702 child.removeLayers(parentLayer);
705 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
711 RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
712 ASSERT(oldParent == layer->parent());
714 oldParent->removeChild(layer);
715 newParent->addChild(layer);
719 for (auto& child : childrenOfType<RenderElement>(*this))
720 child.moveLayers(oldParent, newParent);
723 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
725 // Error check the parent layer passed in. If it's null, we can't find anything.
729 // Step 1: If our layer is a child of the desired parent, then return our layer.
730 RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
731 if (ourLayer && ourLayer->parent() == parentLayer)
734 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
735 // into our siblings trying to find the next layer whose parent is the desired parent.
736 if (!ourLayer || ourLayer == parentLayer) {
737 for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
738 if (!is<RenderElement>(*child))
740 RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
746 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
748 if (parentLayer == ourLayer)
751 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
752 // follow us to see if we can locate a layer.
753 if (checkParent && parent())
754 return parent()->findNextLayer(parentLayer, this, true);
759 bool RenderElement::layerCreationAllowedForSubtree() const
761 RenderElement* parentRenderer = parent();
762 while (parentRenderer) {
763 if (parentRenderer->isSVGHiddenContainer())
765 parentRenderer = parentRenderer->parent();
771 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
773 // FIXME: We could save this call when the change only affected non-inherited properties.
774 for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
775 if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
778 if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
781 #if ENABLE(FULLSCREEN_API)
782 if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
786 // RenderFlowThreads are updated through the RenderView::styleDidChange function.
787 if (is<RenderFlowThread>(elementChild))
790 auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
791 if (style().specifiesColumns()) {
792 if (elementChild.style().specifiesColumns())
793 newStyle.get().inheritColumnPropertiesFrom(&style());
794 if (elementChild.style().columnSpan())
795 newStyle.get().setColumnSpan(ColumnSpanAll);
798 // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
799 // they contain block descendants of relative or sticky positioned inlines.
800 if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
801 newStyle.get().setPosition(elementChild.style().position());
803 elementChild.setStyle(WTF::move(newStyle));
807 static inline bool rendererHasBackground(const RenderElement* renderer)
809 return renderer && renderer->hasBackground();
812 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
814 RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
816 // If our z-index changes value or our visibility changes,
817 // we need to dirty our stacking context's z-order list.
818 bool visibilityChanged = m_style->visibility() != newStyle.visibility()
819 || m_style->zIndex() != newStyle.zIndex()
820 || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
821 #if ENABLE(DASHBOARD_SUPPORT)
822 if (visibilityChanged)
823 document().setAnnotatedRegionsDirty(true);
825 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
826 if (visibilityChanged)
827 document().dirtyTouchEventRects();
829 if (visibilityChanged) {
830 if (AXObjectCache* cache = document().existingAXObjectCache())
831 cache->childrenChanged(parent(), this);
834 // Keep layer hierarchy visibility bits up to date if visibility changes.
835 if (m_style->visibility() != newStyle.visibility()) {
836 if (RenderLayer* layer = enclosingLayer()) {
837 if (newStyle.visibility() == VISIBLE)
838 layer->setHasVisibleContent();
839 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
840 layer->dirtyVisibleContentStatus();
841 if (diff > StyleDifferenceRepaintLayer)
847 if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
849 if (isFloating() && (m_style->floating() != newStyle.floating()))
850 // For changes in float styles, we need to conceivably remove ourselves
851 // from the floating objects list.
852 downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
853 else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
854 // For changes in positioning styles, we need to conceivably remove ourselves
855 // from the positioned objects list.
856 downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
858 s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
859 && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
860 && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
862 s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
863 && parent() && parent()->isRenderBlock();
866 if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
868 clearPositionedState();
870 setHorizontalWritingMode(true);
871 setHasBoxDecorations(false);
872 setHasOverflowClip(false);
873 setHasTransformRelatedProperty(false);
874 setHasReflection(false);
876 s_affectsParentBlock = false;
877 s_noLongerAffectsParentBlock = false;
880 bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
881 bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
882 if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
883 bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
885 bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
886 bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
887 bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
888 if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
889 if (view().compositor().supportsFixedRootBackgroundCompositing()) {
890 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
891 newStyleSlowScroll = false;
893 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
894 oldStyleSlowScroll = false;
898 if (oldStyleSlowScroll != newStyleSlowScroll) {
899 if (oldStyleSlowScroll)
900 view().frameView().removeSlowRepaintObject(this);
902 if (newStyleSlowScroll)
903 view().frameView().addSlowRepaintObject(this);
907 #if ENABLE(CSS_SCROLL_SNAP)
908 if (!newStyle.scrollSnapCoordinates().isEmpty() || (oldStyle && !oldStyle->scrollSnapCoordinates().isEmpty())) {
909 ASSERT(is<RenderBox>(this));
910 if (newStyle.scrollSnapCoordinates().isEmpty())
911 view().unregisterBoxWithScrollSnapCoordinates(downcast<RenderBox>(*this));
913 view().registerBoxWithScrollSnapCoordinates(downcast<RenderBox>(*this));
917 if (isRoot() || isBody())
918 view().frameView().updateExtendBackgroundIfNecessary();
921 void RenderElement::handleDynamicFloatPositionChange()
923 // We have gone from not affecting the inline status of the parent flow to suddenly
924 // having an impact. See if there is a mismatch between the parent flow's
925 // childrenInline() state and our state.
926 setInline(style().isDisplayInlineType());
927 if (isInline() != parent()->childrenInline()) {
929 downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
931 // An anonymous block must be made to wrap this inline.
932 RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
933 parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
934 parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
935 block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
940 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
942 RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
943 if (!parentBlock.canCollapseAnonymousBlockChild())
946 // We have changed to floated or out-of-flow positioning so maybe all our parent's
947 // children can be inline now. Bail if there are any block children left on the line,
948 // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
949 // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
950 // if we find a continuation.
951 RenderObject* current = parent()->firstChild();
952 while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
953 current = current->nextSibling();
959 for (current = parent()->firstChild(); current; current = next) {
960 next = current->nextSibling();
961 if (current->isAnonymousBlock())
962 parentBlock.collapseAnonymousBoxChild(parentBlock, downcast<RenderBlock>(current));
967 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
969 ASSERT(a->cursors() != b->cursors());
970 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
973 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
975 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
979 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
981 if (s_affectsParentBlock)
982 handleDynamicFloatPositionChange();
984 if (s_noLongerAffectsParentBlock)
985 removeAnonymousWrappersForInlinesIfNecessary();
987 SVGRenderSupport::styleChanged(*this, oldStyle);
992 if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
993 RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
995 // If the object already needs layout, then setNeedsLayout won't do
996 // any work. But if the containing block has changed, then we may need
997 // to mark the new containing blocks for layout. The change that can
998 // directly affect the containing block of this object is a change to
999 // the position style.
1000 if (needsLayout() && oldStyle->position() != m_style->position())
1001 markContainingBlocksForLayout();
1003 if (diff == StyleDifferenceLayout)
1004 setNeedsLayoutAndPrefWidthsRecalc();
1006 setNeedsSimplifiedNormalFlowLayout();
1007 } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1008 setNeedsPositionedMovementLayout(oldStyle);
1009 setNeedsSimplifiedNormalFlowLayout();
1010 } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1011 setNeedsPositionedMovementLayout(oldStyle);
1013 // Don't check for repaint here; we need to wait until the layer has been
1014 // updated by subclasses before we know if we have to repaint (in setStyle()).
1017 if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1018 frame().eventHandler().scheduleCursorUpdate();
1022 void RenderElement::insertedIntoTree()
1024 if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1025 containerFlowThread->addFlowChild(*this);
1027 // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1028 // and don't have a layer attached to ourselves.
1029 RenderLayer* layer = nullptr;
1030 if (firstChild() || hasLayer()) {
1031 layer = parent()->enclosingLayer();
1035 // If |this| is visible but this object was not, tell the layer it has some visible content
1036 // that needs to be drawn and layer visibility optimization can't be used
1037 if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1039 layer = parent()->enclosingLayer();
1041 layer->setHasVisibleContent();
1044 RenderObject::insertedIntoTree();
1047 void RenderElement::willBeRemovedFromTree()
1049 // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1050 RenderLayer* layer = nullptr;
1051 if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1052 if ((layer = parent()->enclosingLayer()))
1053 layer->dirtyVisibleContentStatus();
1055 // Keep our layer hierarchy updated.
1056 if (firstChild() || hasLayer()) {
1058 layer = parent()->enclosingLayer();
1059 removeLayers(layer);
1062 if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1063 view().frameView().removeSlowRepaintObject(this);
1065 if (isOutOfFlowPositioned() && parent()->childrenInline())
1066 parent()->dirtyLinesFromChangedChild(*this);
1068 if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1069 containerFlowThread->removeFlowChild(*this);
1072 #if ENABLE(CSS_SCROLL_SNAP)
1073 if (!m_style->scrollSnapCoordinates().isEmpty()) {
1074 ASSERT(is<RenderBox>(this));
1075 view().unregisterBoxWithScrollSnapCoordinates(downcast<RenderBox>(*this));
1079 RenderObject::willBeRemovedFromTree();
1082 void RenderElement::willBeDestroyed()
1084 animation().cancelAnimations(*this);
1086 destroyLeftoverChildren();
1088 if (hasCounterNodeMap())
1089 RenderCounter::destroyCounterNodes(*this);
1091 RenderObject::willBeDestroyed();
1093 #if !ASSERT_DISABLED
1094 if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1095 // After remove, the object and the associated information should not be in any flow thread.
1096 for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1097 ASSERT(!flowThread->hasChild(*this));
1098 ASSERT(!flowThread->hasChildInfo(this));
1104 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1106 ASSERT(!isSetNeedsLayoutForbidden());
1107 if (needsPositionedMovementLayout())
1109 setNeedsPositionedMovementLayoutBit(true);
1110 markContainingBlocksForLayout();
1112 if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1113 setLayerNeedsFullRepaint();
1115 setLayerNeedsFullRepaintForPositionedMovementLayout();
1119 void RenderElement::clearChildNeedsLayout()
1121 setNormalChildNeedsLayoutBit(false);
1122 setPosChildNeedsLayoutBit(false);
1123 setNeedsSimplifiedNormalFlowLayoutBit(false);
1124 setNormalChildNeedsLayoutBit(false);
1125 setNeedsPositionedMovementLayoutBit(false);
1128 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1130 ASSERT(!isSetNeedsLayoutForbidden());
1131 if (needsSimplifiedNormalFlowLayout())
1133 setNeedsSimplifiedNormalFlowLayoutBit(true);
1134 markContainingBlocksForLayout();
1136 setLayerNeedsFullRepaint();
1139 RenderElement& RenderElement::rendererForRootBackground()
1142 if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1143 // Locate the <body> element using the DOM. This is easier than trying
1144 // to crawl around a render tree with potential :before/:after content and
1145 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1146 // render object very easily via the DOM.
1147 if (auto* body = document().body()) {
1148 if (auto* renderer = body->renderer())
1155 RenderElement* RenderElement::hoverAncestor() const
1157 // When searching for the hover ancestor and encountering a named flow thread,
1158 // the search will continue with the DOM ancestor of the top-most element
1159 // in the named flow thread.
1160 // See https://bugs.webkit.org/show_bug.cgi?id=111749
1161 RenderElement* hoverAncestor = parent();
1163 // Skip anonymous blocks directly flowed into flow threads as it would
1164 // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1165 if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1166 hoverAncestor = hoverAncestor->parent();
1168 if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1169 hoverAncestor = nullptr;
1170 if (Element* element = this->element()) {
1171 if (auto parent = element->parentNode())
1172 hoverAncestor = parent->renderer();
1176 return hoverAncestor;
1179 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1181 paintInfo.phase = phase;
1182 element.paint(paintInfo, childPoint);
1185 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1187 // Paint all phases atomically, as though the element established its own stacking context.
1188 // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1189 // This is also used by other elements (e.g. flex items and grid items).
1190 if (paintInfo.phase == PaintPhaseSelection) {
1191 paint(paintInfo, childPoint);
1192 } else if (paintInfo.phase == PaintPhaseForeground) {
1193 paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1194 paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1195 paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1196 paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1197 paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1199 // Reset |paintInfo| to the original phase.
1200 paintInfo.phase = PaintPhaseForeground;
1204 void RenderElement::layout()
1206 StackStats::LayoutCheckPoint layoutCheckPoint;
1207 ASSERT(needsLayout());
1208 RenderObject* child = firstChild();
1210 if (child->needsLayout())
1211 downcast<RenderElement>(*child).layout();
1212 ASSERT(!child->needsLayout());
1213 child = child->nextSibling();
1218 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1220 // Nobody will use multiple layers without wanting fancy positioning.
1224 // Make sure we have a valid image.
1225 StyleImage* image = layer->image();
1226 if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1229 if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1232 EFillSizeType sizeType = layer->sizeType();
1234 if (sizeType == Contain || sizeType == Cover)
1237 if (sizeType == SizeLength) {
1238 LengthSize size = layer->sizeLength();
1239 if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1241 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1242 if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1244 } else if (image->usesImageContainerSize())
1250 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1252 if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1255 // If we don't have a background/border/mask, then nothing to do.
1256 if (!renderer.hasBoxDecorations())
1259 if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1262 // Our fill layers are ok. Let's check border.
1263 if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1269 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1271 if (view().printing())
1272 return false; // Don't repaint if we're printing.
1274 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1275 // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1276 LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1277 LayoutRect newOutlineBox;
1279 bool fullRepaint = selfNeedsLayout();
1280 // Presumably a background or a border exists if border-fit:lines was specified.
1281 if (!fullRepaint && style().borderFit() == BorderFitLines)
1284 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1285 // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1286 newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1287 if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1291 if (!repaintContainer)
1292 repaintContainer = &view();
1295 repaintUsingContainer(repaintContainer, oldBounds);
1296 if (newBounds != oldBounds)
1297 repaintUsingContainer(repaintContainer, newBounds);
1301 if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1304 LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1306 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1307 else if (deltaLeft < 0)
1308 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1310 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1312 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1313 else if (deltaRight < 0)
1314 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1316 LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1318 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1319 else if (deltaTop < 0)
1320 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1322 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1323 if (deltaBottom > 0)
1324 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1325 else if (deltaBottom < 0)
1326 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1328 if (newOutlineBox == oldOutlineBox)
1331 // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1332 // two rectangles (but typically only one).
1333 const RenderStyle& outlineStyle = outlineStyleForRepaint();
1334 LayoutUnit outlineWidth = outlineStyle.outlineSize();
1335 LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1336 LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1338 LayoutUnit shadowLeft;
1339 LayoutUnit shadowRight;
1340 style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1341 LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1342 LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1343 LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1344 LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1345 LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1346 LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1348 width + decorationsWidth,
1349 std::max(newOutlineBox.height(), oldOutlineBox.height()));
1350 LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1351 if (rightRect.x() < right) {
1352 rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1353 repaintUsingContainer(repaintContainer, rightRect);
1356 LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1358 LayoutUnit shadowTop;
1359 LayoutUnit shadowBottom;
1360 style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1361 LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1362 LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1363 LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1364 LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1365 valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1366 LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1367 LayoutRect bottomRect(newOutlineBox.x(),
1368 std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1369 std::max(newOutlineBox.width(), oldOutlineBox.width()),
1370 height + decorationsHeight);
1371 LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1372 if (bottomRect.y() < bottom) {
1373 bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1374 repaintUsingContainer(repaintContainer, bottomRect);
1380 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1382 ASSERT(style().hasBorder());
1384 StyleImage* borderImage = style().borderImage().image();
1385 return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1388 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1390 auto& frameView = view().frameView();
1391 if (frameView.isOffscreen())
1394 if (!hasOverflowClip()) {
1395 // FIXME: Computing the overflow rect is expensive if any descendant has
1396 // its own self-painting layer. As a result, we prefer to abort early in
1397 // this case and assume it may cause us to repaint inside the viewport.
1398 if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1402 // Compute viewport rect if it was not provided.
1403 const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1404 return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1407 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1409 const Document& document = renderer.document();
1410 if (document.inPageCache())
1413 if (document.frame()->timersPaused())
1416 if (document.activeDOMObjectsAreSuspended())
1418 if (renderer.style().visibility() != VISIBLE)
1420 if (renderer.view().frameView().isOffscreen())
1423 // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1424 // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1425 // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1426 // can no longer check if it is a background image.
1427 bool backgroundIsPaintedByRoot = renderer.isRoot();
1428 if (renderer.isBody()) {
1429 auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1430 ASSERT(rootRenderer.isRoot());
1431 ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1432 // FIXME: Should share body background propagation code.
1433 backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1436 LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect(&renderer.view()) : renderer.absoluteClippedOverflowRect();
1437 if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1443 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1445 if (document().inPageCache())
1447 auto& frameView = view().frameView();
1448 auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1449 if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1450 // FIXME: It would be better to pass the image along with the renderer
1451 // so that we can be smarter about detecting if the image is inside the
1452 // viewport in repaintForPausedImageAnimationsIfNeeded().
1453 view().addRendererWithPausedImageAnimations(*this);
1456 imageChanged(&image);
1459 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1461 ASSERT(m_hasPausedImageAnimations);
1462 if (!shouldRepaintForImageAnimation(*this, visibleRect))
1468 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1470 auto* renderer = this;
1471 while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1472 renderer = renderer->parent();
1473 return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1476 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1478 return controlStatesRendererMap().contains(o);
1481 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1483 return controlStatesRendererMap().get(o);
1486 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1488 ControlStates* states = controlStatesRendererMap().get(o);
1490 controlStatesRendererMap().remove(o);
1495 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1497 controlStatesRendererMap().add(o, states);
1500 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1502 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1505 RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1509 RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1511 return style().addCachedPseudoStyle(result.release());
1515 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1517 if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1522 parentStyle = &style();
1528 if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1529 RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element(), parentStyle, DisallowStyleSharing);
1530 result->setStyleType(FIRST_LINE_INHERITED);
1531 return result.release();
1534 return document().ensureStyleResolver().pseudoStyleForElement(element(), pseudoStyleRequest, parentStyle);
1537 RenderBlock* RenderElement::containingBlockForFixedPosition() const
1539 const RenderElement* object = this;
1540 while (object && !object->canContainFixedPositionObjects())
1541 object = object->parent();
1543 ASSERT(!object || !object->isAnonymousBlock());
1544 return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1547 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
1549 const RenderElement* object = this;
1550 while (object && !object->canContainAbsolutelyPositionedObjects())
1551 object = object->parent();
1553 // For a relatively positioned inline, return its nearest non-anonymous containing block,
1554 // not the inline itself, to avoid having a positioned objects list in all RenderInlines
1555 // and use RenderBlock* as RenderElement::containingBlock's return type.
1556 // Use RenderBlock::container() to obtain the inline.
1557 if (object && !is<RenderBlock>(*object))
1558 object = object->containingBlock();
1560 while (object && object->isAnonymousBlock())
1561 object = object->containingBlock();
1563 return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1566 static inline bool isNonRenderBlockInline(const RenderElement& object)
1568 return (object.isInline() && !object.isReplaced()) || !object.isRenderBlock();
1571 RenderBlock* RenderElement::containingBlockForObjectInFlow() const
1573 const RenderElement* object = this;
1574 while (object && isNonRenderBlockInline(*object))
1575 object = object->parent();
1576 return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1579 Color RenderElement::selectionColor(int colorProperty) const
1581 // If the element is unselectable, or we are only painting the selection,
1582 // don't override the foreground color with the selection foreground color.
1583 if (style().userSelect() == SELECT_NONE
1584 || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1587 if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1588 Color color = pseudoStyle->visitedDependentColor(colorProperty);
1589 if (!color.isValid())
1590 color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1594 if (frame().selection().isFocusedAndActive())
1595 return theme().activeSelectionForegroundColor();
1596 return theme().inactiveSelectionForegroundColor();
1599 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1604 if (ShadowRoot* root = element()->containingShadowRoot()) {
1605 if (root->type() == ShadowRoot::UserAgentShadowRoot) {
1606 if (Element* shadowHost = element()->shadowHost())
1607 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1611 return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1614 Color RenderElement::selectionForegroundColor() const
1616 return selectionColor(CSSPropertyWebkitTextFillColor);
1619 Color RenderElement::selectionEmphasisMarkColor() const
1621 return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1624 Color RenderElement::selectionBackgroundColor() const
1626 if (style().userSelect() == SELECT_NONE)
1629 if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1630 return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1632 RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1633 if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1634 return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1636 if (frame().selection().isFocusedAndActive())
1637 return theme().activeSelectionBackgroundColor();
1638 return theme().inactiveSelectionBackgroundColor();
1641 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1643 if (!isInline() || isReplaced()) {
1644 point = localToAbsolute(FloatPoint(), UseTransforms);
1648 // find the next text/image child, to get a position
1649 const RenderObject* o = this;
1651 const RenderObject* p = o;
1652 if (RenderObject* child = o->firstChildSlow())
1654 else if (o->nextSibling())
1655 o = o->nextSibling();
1657 RenderObject* next = 0;
1658 while (!next && o->parent()) {
1660 next = o->nextSibling();
1669 if (!o->isInline() || o->isReplaced()) {
1670 point = o->localToAbsolute(FloatPoint(), UseTransforms);
1674 if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1675 // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1676 } else if (is<RenderText>(*o) || o->isReplaced()) {
1677 point = FloatPoint();
1678 if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1679 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1680 else if (is<RenderBox>(*o))
1681 point.moveBy(downcast<RenderBox>(*o).location());
1682 point = o->container()->localToAbsolute(point, UseTransforms);
1687 // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1688 // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1689 if (!o && document().view()) {
1690 point = FloatPoint(0, document().view()->contentsHeight());
1696 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1698 if (!isInline() || isReplaced()) {
1699 point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1703 // find the last text/image child, to get a position
1704 const RenderObject* o = this;
1706 if (RenderObject* child = o->lastChildSlow())
1708 else if (o->previousSibling())
1709 o = o->previousSibling();
1711 RenderObject* prev = 0;
1716 prev = o->previousSibling();
1721 if (is<RenderText>(*o) || o->isReplaced()) {
1722 point = FloatPoint();
1723 if (is<RenderText>(*o)) {
1724 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1725 if (!linesBox.maxX() && !linesBox.maxY())
1727 point.moveBy(linesBox.maxXMaxYCorner());
1729 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1730 point = o->container()->localToAbsolute(point, UseTransforms);
1737 LayoutRect RenderElement::anchorRect() const
1739 FloatPoint leading, trailing;
1740 getLeadingCorner(leading);
1741 getTrailingCorner(trailing);
1743 FloatPoint upperLeft = leading;
1744 FloatPoint lowerRight = trailing;
1746 // Vertical writing modes might mean the leading point is not in the top left
1747 if (!isInline() || isReplaced()) {
1748 upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1749 lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1750 } // Otherwise, it's not obvious what to do.
1752 return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1755 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1757 const RenderElement* current = this;
1759 if (current->isRenderBlock())
1761 if (!current->isRenderInline() || current->isRubyText())
1764 const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1765 if (styleToUse.textDecoration() & textDecoration)
1767 current = current->parent();
1768 } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));