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 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()) {
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());
411 ASSERT(minimalStyleDifference == StyleDifferenceEqual);
415 StyleDifference diff = StyleDifferenceEqual;
416 unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
417 if (m_hasInitializedStyle)
418 diff = m_style->diff(style.get(), contextSensitiveProperties);
420 diff = std::max(diff, minimalStyleDifference);
422 diff = adjustStyleDifference(diff, contextSensitiveProperties);
424 styleWillChange(diff, style.get());
426 Ref<RenderStyle> oldStyle(m_style.replace(WTF::move(style)));
428 updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
429 updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
431 updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
432 updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
434 #if ENABLE(CSS_SHAPES)
435 updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
438 // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
439 // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
440 if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
441 view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
443 bool doesNotNeedLayout = !parent();
445 styleDidChange(diff, oldStyle.ptr());
447 // Text renderers use their parent style. Notify them about the change.
448 for (auto& child : childrenOfType<RenderText>(*this))
449 child.styleDidChange(diff, oldStyle.ptr());
451 // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
452 // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
453 // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
454 // in the future as we move renderer changes out of layout and into style changes.
455 if (doesNotNeedLayout)
458 // Now that the layer (if any) has been updated, we need to adjust the diff again,
459 // check whether we should layout now, and decide if we need to repaint.
460 StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
462 if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
463 if (updatedDiff == StyleDifferenceLayout)
464 setNeedsLayoutAndPrefWidthsRecalc();
465 else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
466 setNeedsPositionedMovementLayout(oldStyle.ptr());
467 else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
468 setNeedsPositionedMovementLayout(oldStyle.ptr());
469 setNeedsSimplifiedNormalFlowLayout();
470 } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
471 setNeedsSimplifiedNormalFlowLayout();
474 if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
475 // Do a repaint with the new style now, e.g., for example if we go from
476 // not having an outline to having an outline.
481 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
483 bool needsTable = false;
485 if (is<RenderTableCol>(*newChild)) {
486 RenderTableCol& newTableColumn = downcast<RenderTableCol>(*newChild);
487 bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
488 needsTable = !is<RenderTable>(*this) && !isColumnInColumnGroup;
489 } else if (is<RenderTableCaption>(*newChild))
490 needsTable = !is<RenderTable>(*this);
491 else if (is<RenderTableSection>(*newChild))
492 needsTable = !is<RenderTable>(*this);
493 else if (is<RenderTableRow>(*newChild))
494 needsTable = !is<RenderTableSection>(*this);
495 else if (is<RenderTableCell>(*newChild))
496 needsTable = !is<RenderTableRow>(*this);
500 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
501 if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
502 table = downcast<RenderTable>(afterChild);
504 table = RenderTable::createAnonymousWithParentRenderer(this);
505 addChild(table, beforeChild);
507 table->addChild(newChild);
509 insertChildInternal(newChild, beforeChild, NotifyChildren);
511 if (is<RenderText>(*newChild))
512 downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
514 // SVG creates renderers for <g display="none">, as SVG requires children of hidden
515 // <g>s to have renderers - at least that's how our implementation works. Consider:
516 // <g display="none"><foreignObject><body style="position: relative">FOO...
517 // - requiresLayer() would return true for the <body>, creating a new RenderLayer
518 // - when the document is painted, both layers are painted. The <body> layer doesn't
519 // know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
520 // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
521 // and stop creating layers at all for these cases - they're not used anyways.
522 if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
523 downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
525 SVGRenderSupport::childAdded(*this, *newChild);
528 void RenderElement::removeChild(RenderObject& oldChild)
530 removeChildInternal(oldChild, NotifyChildren);
533 void RenderElement::destroyLeftoverChildren()
535 while (m_firstChild) {
536 if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
537 m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
539 // 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.
540 if (m_firstChild->node())
541 m_firstChild->node()->setRenderer(nullptr);
542 m_firstChild->destroy();
547 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
549 ASSERT(canHaveChildren() || canHaveGeneratedChildren());
550 ASSERT(!newChild->parent());
551 ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
553 while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
554 beforeChild = beforeChild->parent();
556 // This should never happen, but if it does prevent render tree corruption
557 // where child->parent() ends up being owner but child->nextSibling()->parent()
559 if (beforeChild && beforeChild->parent() != this) {
560 ASSERT_NOT_REACHED();
564 newChild->setParent(this);
566 if (m_firstChild == beforeChild)
567 m_firstChild = newChild;
570 RenderObject* previousSibling = beforeChild->previousSibling();
572 previousSibling->setNextSibling(newChild);
573 newChild->setPreviousSibling(previousSibling);
574 newChild->setNextSibling(beforeChild);
575 beforeChild->setPreviousSibling(newChild);
578 lastChild()->setNextSibling(newChild);
579 newChild->setPreviousSibling(lastChild());
580 m_lastChild = newChild;
583 if (!documentBeingDestroyed()) {
584 if (notifyChildren == NotifyChildren)
585 newChild->insertedIntoTree();
586 if (is<RenderElement>(*newChild))
587 RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
590 newChild->setNeedsLayoutAndPrefWidthsRecalc();
591 setPreferredLogicalWidthsDirty(true);
592 if (!normalChildNeedsLayout())
593 setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
595 if (AXObjectCache* cache = document().axObjectCache())
596 cache->childrenChanged(this, newChild);
599 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
601 ASSERT(canHaveChildren() || canHaveGeneratedChildren());
602 ASSERT(oldChild.parent() == this);
604 if (oldChild.isFloatingOrOutOfFlowPositioned())
605 downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
607 // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
608 // that a positioned child got yanked). We also repaint, so that the area exposed when the child
609 // disappears gets repainted properly.
610 if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
611 oldChild.setNeedsLayoutAndPrefWidthsRecalc();
612 // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
613 if (oldChild.isBody())
614 view().repaintRootContents();
619 // If we have a line box wrapper, delete it.
620 if (is<RenderBox>(oldChild))
621 downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
622 else if (is<RenderLineBreak>(oldChild))
623 downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
625 // If oldChild is the start or end of the selection, then clear the selection to
626 // avoid problems of invalid pointers.
627 if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
628 frame().selection().setNeedsSelectionUpdate();
630 if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
631 oldChild.willBeRemovedFromTree();
633 // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
634 // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
635 // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
637 RenderObject* nextSibling = oldChild.nextSibling();
639 if (oldChild.previousSibling())
640 oldChild.previousSibling()->setNextSibling(nextSibling);
642 nextSibling->setPreviousSibling(oldChild.previousSibling());
644 if (m_firstChild == &oldChild)
645 m_firstChild = nextSibling;
646 if (m_lastChild == &oldChild)
647 m_lastChild = oldChild.previousSibling();
649 oldChild.setPreviousSibling(nullptr);
650 oldChild.setNextSibling(nullptr);
651 oldChild.setParent(nullptr);
653 // rendererRemovedFromTree walks the whole subtree. We can improve performance
654 // by skipping this step when destroying the entire tree.
655 if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
656 RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
658 if (AXObjectCache* cache = document().existingAXObjectCache())
659 cache->childrenChanged(this);
662 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
664 if (renderer.hasLayer()) {
665 if (!beforeChild && newObject) {
666 // We need to figure out the layer that follows newObject. We only do
667 // this the first time we find a child layer, and then we update the
668 // pointer values for newObject and beforeChild used by everyone else.
669 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
672 parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
676 for (auto& child : childrenOfType<RenderElement>(renderer))
677 addLayers(child, parentLayer, newObject, beforeChild);
680 void RenderElement::addLayers(RenderLayer* parentLayer)
685 RenderElement* renderer = this;
686 RenderLayer* beforeChild = nullptr;
687 WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
690 void RenderElement::removeLayers(RenderLayer* parentLayer)
696 parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
700 for (auto& child : childrenOfType<RenderElement>(*this))
701 child.removeLayers(parentLayer);
704 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
710 RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
711 ASSERT(oldParent == layer->parent());
713 oldParent->removeChild(layer);
714 newParent->addChild(layer);
718 for (auto& child : childrenOfType<RenderElement>(*this))
719 child.moveLayers(oldParent, newParent);
722 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
724 // Error check the parent layer passed in. If it's null, we can't find anything.
728 // Step 1: If our layer is a child of the desired parent, then return our layer.
729 RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
730 if (ourLayer && ourLayer->parent() == parentLayer)
733 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
734 // into our siblings trying to find the next layer whose parent is the desired parent.
735 if (!ourLayer || ourLayer == parentLayer) {
736 for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
737 if (!is<RenderElement>(*child))
739 RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
745 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
747 if (parentLayer == ourLayer)
750 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
751 // follow us to see if we can locate a layer.
752 if (checkParent && parent())
753 return parent()->findNextLayer(parentLayer, this, true);
758 bool RenderElement::layerCreationAllowedForSubtree() const
760 RenderElement* parentRenderer = parent();
761 while (parentRenderer) {
762 if (parentRenderer->isSVGHiddenContainer())
764 parentRenderer = parentRenderer->parent();
770 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
772 // FIXME: We could save this call when the change only affected non-inherited properties.
773 for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
774 if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
777 if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
780 #if ENABLE(FULLSCREEN_API)
781 if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
785 // RenderFlowThreads are updated through the RenderView::styleDidChange function.
786 if (is<RenderFlowThread>(elementChild))
789 auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
790 if (style().specifiesColumns()) {
791 if (elementChild.style().specifiesColumns())
792 newStyle.get().inheritColumnPropertiesFrom(&style());
793 if (elementChild.style().columnSpan())
794 newStyle.get().setColumnSpan(ColumnSpanAll);
797 // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
798 // they contain block descendants of relative or sticky positioned inlines.
799 if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
800 newStyle.get().setPosition(elementChild.style().position());
802 elementChild.setStyle(WTF::move(newStyle));
806 static inline bool rendererHasBackground(const RenderElement* renderer)
808 return renderer && renderer->hasBackground();
811 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
813 RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
815 // If our z-index changes value or our visibility changes,
816 // we need to dirty our stacking context's z-order list.
817 bool visibilityChanged = m_style->visibility() != newStyle.visibility()
818 || m_style->zIndex() != newStyle.zIndex()
819 || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
820 #if ENABLE(DASHBOARD_SUPPORT)
821 if (visibilityChanged)
822 document().setAnnotatedRegionsDirty(true);
824 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
825 if (visibilityChanged)
826 document().dirtyTouchEventRects();
828 if (visibilityChanged) {
829 if (AXObjectCache* cache = document().existingAXObjectCache())
830 cache->childrenChanged(parent(), this);
833 // Keep layer hierarchy visibility bits up to date if visibility changes.
834 if (m_style->visibility() != newStyle.visibility()) {
835 if (RenderLayer* layer = enclosingLayer()) {
836 if (newStyle.visibility() == VISIBLE)
837 layer->setHasVisibleContent();
838 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
839 layer->dirtyVisibleContentStatus();
840 if (diff > StyleDifferenceRepaintLayer)
846 if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
848 if (isFloating() && (m_style->floating() != newStyle.floating()))
849 // For changes in float styles, we need to conceivably remove ourselves
850 // from the floating objects list.
851 downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
852 else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
853 // For changes in positioning styles, we need to conceivably remove ourselves
854 // from the positioned objects list.
855 downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
857 s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
858 && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
859 && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
861 s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
862 && parent() && parent()->isRenderBlock();
865 if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
867 clearPositionedState();
869 setHorizontalWritingMode(true);
870 setHasBoxDecorations(false);
871 setHasOverflowClip(false);
872 setHasTransformRelatedProperty(false);
873 setHasReflection(false);
875 s_affectsParentBlock = false;
876 s_noLongerAffectsParentBlock = false;
879 bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
880 bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
881 if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
882 bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
884 bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
885 bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
886 bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
887 if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
888 if (view().compositor().supportsFixedRootBackgroundCompositing()) {
889 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
890 newStyleSlowScroll = false;
892 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
893 oldStyleSlowScroll = false;
897 if (oldStyleSlowScroll != newStyleSlowScroll) {
898 if (oldStyleSlowScroll)
899 view().frameView().removeSlowRepaintObject(this);
901 if (newStyleSlowScroll)
902 view().frameView().addSlowRepaintObject(this);
906 if (isRoot() || isBody())
907 view().frameView().updateExtendBackgroundIfNecessary();
910 void RenderElement::handleDynamicFloatPositionChange()
912 // We have gone from not affecting the inline status of the parent flow to suddenly
913 // having an impact. See if there is a mismatch between the parent flow's
914 // childrenInline() state and our state.
915 setInline(style().isDisplayInlineType());
916 if (isInline() != parent()->childrenInline()) {
918 downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
920 // An anonymous block must be made to wrap this inline.
921 RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
922 parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
923 parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
924 block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
929 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
931 RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
932 if (!parentBlock.canCollapseAnonymousBlockChild())
935 // We have changed to floated or out-of-flow positioning so maybe all our parent's
936 // children can be inline now. Bail if there are any block children left on the line,
937 // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
938 // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
939 // if we find a continuation.
940 RenderObject* current = parent()->firstChild();
941 while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
942 current = current->nextSibling();
948 for (current = parent()->firstChild(); current; current = next) {
949 next = current->nextSibling();
950 if (current->isAnonymousBlock())
951 parentBlock.collapseAnonymousBoxChild(parentBlock, downcast<RenderBlock>(current));
956 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
958 ASSERT(a->cursors() != b->cursors());
959 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
962 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
964 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
968 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
970 if (s_affectsParentBlock)
971 handleDynamicFloatPositionChange();
973 if (s_noLongerAffectsParentBlock)
974 removeAnonymousWrappersForInlinesIfNecessary();
976 SVGRenderSupport::styleChanged(*this, oldStyle);
981 if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
982 RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
984 // If the object already needs layout, then setNeedsLayout won't do
985 // any work. But if the containing block has changed, then we may need
986 // to mark the new containing blocks for layout. The change that can
987 // directly affect the containing block of this object is a change to
988 // the position style.
989 if (needsLayout() && oldStyle->position() != m_style->position())
990 markContainingBlocksForLayout();
992 if (diff == StyleDifferenceLayout)
993 setNeedsLayoutAndPrefWidthsRecalc();
995 setNeedsSimplifiedNormalFlowLayout();
996 } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
997 setNeedsPositionedMovementLayout(oldStyle);
998 setNeedsSimplifiedNormalFlowLayout();
999 } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1000 setNeedsPositionedMovementLayout(oldStyle);
1002 // Don't check for repaint here; we need to wait until the layer has been
1003 // updated by subclasses before we know if we have to repaint (in setStyle()).
1006 if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1007 frame().eventHandler().scheduleCursorUpdate();
1011 void RenderElement::insertedIntoTree()
1013 if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1014 containerFlowThread->addFlowChild(*this);
1016 // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1017 // and don't have a layer attached to ourselves.
1018 RenderLayer* layer = nullptr;
1019 if (firstChild() || hasLayer()) {
1020 layer = parent()->enclosingLayer();
1024 // If |this| is visible but this object was not, tell the layer it has some visible content
1025 // that needs to be drawn and layer visibility optimization can't be used
1026 if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1028 layer = parent()->enclosingLayer();
1030 layer->setHasVisibleContent();
1033 RenderObject::insertedIntoTree();
1036 void RenderElement::willBeRemovedFromTree()
1038 // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1039 RenderLayer* layer = nullptr;
1040 if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1041 if ((layer = parent()->enclosingLayer()))
1042 layer->dirtyVisibleContentStatus();
1044 // Keep our layer hierarchy updated.
1045 if (firstChild() || hasLayer()) {
1047 layer = parent()->enclosingLayer();
1048 removeLayers(layer);
1051 if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1052 view().frameView().removeSlowRepaintObject(this);
1054 if (isOutOfFlowPositioned() && parent()->childrenInline())
1055 parent()->dirtyLinesFromChangedChild(*this);
1057 if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1058 containerFlowThread->removeFlowChild(*this);
1060 RenderObject::willBeRemovedFromTree();
1063 void RenderElement::willBeDestroyed()
1065 animation().cancelAnimations(*this);
1067 destroyLeftoverChildren();
1069 if (hasCounterNodeMap())
1070 RenderCounter::destroyCounterNodes(*this);
1072 RenderObject::willBeDestroyed();
1074 #if !ASSERT_DISABLED
1075 if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1076 // After remove, the object and the associated information should not be in any flow thread.
1077 for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1078 ASSERT(!flowThread->hasChild(*this));
1079 ASSERT(!flowThread->hasChildInfo(this));
1085 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1087 ASSERT(!isSetNeedsLayoutForbidden());
1088 if (needsPositionedMovementLayout())
1090 setNeedsPositionedMovementLayoutBit(true);
1091 markContainingBlocksForLayout();
1093 if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1094 setLayerNeedsFullRepaint();
1096 setLayerNeedsFullRepaintForPositionedMovementLayout();
1100 void RenderElement::clearChildNeedsLayout()
1102 setNormalChildNeedsLayoutBit(false);
1103 setPosChildNeedsLayoutBit(false);
1104 setNeedsSimplifiedNormalFlowLayoutBit(false);
1105 setNormalChildNeedsLayoutBit(false);
1106 setNeedsPositionedMovementLayoutBit(false);
1109 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1111 ASSERT(!isSetNeedsLayoutForbidden());
1112 if (needsSimplifiedNormalFlowLayout())
1114 setNeedsSimplifiedNormalFlowLayoutBit(true);
1115 markContainingBlocksForLayout();
1117 setLayerNeedsFullRepaint();
1120 RenderElement& RenderElement::rendererForRootBackground()
1123 if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1124 // Locate the <body> element using the DOM. This is easier than trying
1125 // to crawl around a render tree with potential :before/:after content and
1126 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1127 // render object very easily via the DOM.
1128 if (auto* body = document().body()) {
1129 if (auto* renderer = body->renderer())
1136 RenderElement* RenderElement::hoverAncestor() const
1138 // When searching for the hover ancestor and encountering a named flow thread,
1139 // the search will continue with the DOM ancestor of the top-most element
1140 // in the named flow thread.
1141 // See https://bugs.webkit.org/show_bug.cgi?id=111749
1142 RenderElement* hoverAncestor = parent();
1144 // Skip anonymous blocks directly flowed into flow threads as it would
1145 // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1146 if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1147 hoverAncestor = hoverAncestor->parent();
1149 if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1150 hoverAncestor = nullptr;
1151 if (Element* element = this->element()) {
1152 if (auto parent = element->parentNode())
1153 hoverAncestor = parent->renderer();
1157 return hoverAncestor;
1160 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1162 paintInfo.phase = phase;
1163 element.paint(paintInfo, childPoint);
1166 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1168 // Paint all phases atomically, as though the element established its own stacking context.
1169 // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1170 // This is also used by other elements (e.g. flex items and grid items).
1171 if (paintInfo.phase == PaintPhaseSelection) {
1172 paint(paintInfo, childPoint);
1173 } else if (paintInfo.phase == PaintPhaseForeground) {
1174 paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1175 paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1176 paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1177 paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1178 paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1180 // Reset |paintInfo| to the original phase.
1181 paintInfo.phase = PaintPhaseForeground;
1185 void RenderElement::layout()
1187 StackStats::LayoutCheckPoint layoutCheckPoint;
1188 ASSERT(needsLayout());
1189 RenderObject* child = firstChild();
1191 if (child->needsLayout())
1192 downcast<RenderElement>(*child).layout();
1193 ASSERT(!child->needsLayout());
1194 child = child->nextSibling();
1199 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1201 // Nobody will use multiple layers without wanting fancy positioning.
1205 // Make sure we have a valid image.
1206 StyleImage* image = layer->image();
1207 if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1210 if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1213 EFillSizeType sizeType = layer->sizeType();
1215 if (sizeType == Contain || sizeType == Cover)
1218 if (sizeType == SizeLength) {
1219 LengthSize size = layer->sizeLength();
1220 if (size.width().isPercent() || size.height().isPercent())
1222 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1223 if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1225 } else if (image->usesImageContainerSize())
1231 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1233 if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1236 // If we don't have a background/border/mask, then nothing to do.
1237 if (!renderer.hasBoxDecorations())
1240 if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1243 // Our fill layers are ok. Let's check border.
1244 if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1250 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1252 if (view().printing())
1253 return false; // Don't repaint if we're printing.
1255 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1256 // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1257 LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1258 LayoutRect newOutlineBox;
1260 bool fullRepaint = selfNeedsLayout();
1261 // Presumably a background or a border exists if border-fit:lines was specified.
1262 if (!fullRepaint && style().borderFit() == BorderFitLines)
1265 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1266 // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1267 newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1268 if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1272 if (!repaintContainer)
1273 repaintContainer = &view();
1276 repaintUsingContainer(repaintContainer, oldBounds);
1277 if (newBounds != oldBounds)
1278 repaintUsingContainer(repaintContainer, newBounds);
1282 if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1285 LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1287 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1288 else if (deltaLeft < 0)
1289 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1291 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1293 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1294 else if (deltaRight < 0)
1295 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1297 LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1299 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1300 else if (deltaTop < 0)
1301 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1303 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1304 if (deltaBottom > 0)
1305 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1306 else if (deltaBottom < 0)
1307 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1309 if (newOutlineBox == oldOutlineBox)
1312 // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1313 // two rectangles (but typically only one).
1314 const RenderStyle& outlineStyle = outlineStyleForRepaint();
1315 LayoutUnit outlineWidth = outlineStyle.outlineSize();
1316 LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1317 LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1319 LayoutUnit shadowLeft;
1320 LayoutUnit shadowRight;
1321 style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1322 LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1323 LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1324 LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1325 LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1326 LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1327 LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1329 width + decorationsWidth,
1330 std::max(newOutlineBox.height(), oldOutlineBox.height()));
1331 LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1332 if (rightRect.x() < right) {
1333 rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1334 repaintUsingContainer(repaintContainer, rightRect);
1337 LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1339 LayoutUnit shadowTop;
1340 LayoutUnit shadowBottom;
1341 style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1342 LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1343 LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1344 LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1345 LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1346 valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1347 LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1348 LayoutRect bottomRect(newOutlineBox.x(),
1349 std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1350 std::max(newOutlineBox.width(), oldOutlineBox.width()),
1351 height + decorationsHeight);
1352 LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1353 if (bottomRect.y() < bottom) {
1354 bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1355 repaintUsingContainer(repaintContainer, bottomRect);
1361 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1363 ASSERT(style().hasBorder());
1365 StyleImage* borderImage = style().borderImage().image();
1366 return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1369 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1371 auto& frameView = view().frameView();
1372 if (frameView.isOffscreen())
1375 if (!hasOverflowClip()) {
1376 // FIXME: Computing the overflow rect is expensive if any descendant has
1377 // its own self-painting layer. As a result, we prefer to abort early in
1378 // this case and assume it may cause us to repaint inside the viewport.
1379 if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1383 // Compute viewport rect if it was not provided.
1384 const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1385 return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1388 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1390 const Document& document = renderer.document();
1391 if (document.inPageCache())
1394 if (document.frame()->timersPaused())
1397 if (document.activeDOMObjectsAreSuspended())
1399 if (renderer.style().visibility() != VISIBLE)
1401 if (renderer.view().frameView().isOffscreen())
1404 // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1405 // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1406 // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1407 // can no longer check if it is a background image.
1408 bool backgroundIsPaintedByRoot = renderer.isRoot();
1409 if (renderer.isBody()) {
1410 auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1411 ASSERT(rootRenderer.isRoot());
1412 ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1413 // FIXME: Should share body background propagation code.
1414 backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1417 LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect(&renderer.view()) : renderer.absoluteClippedOverflowRect();
1418 if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1424 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1426 if (document().inPageCache())
1428 auto& frameView = view().frameView();
1429 auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1430 if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1431 // FIXME: It would be better to pass the image along with the renderer
1432 // so that we can be smarter about detecting if the image is inside the
1433 // viewport in repaintForPausedImageAnimationsIfNeeded().
1434 view().addRendererWithPausedImageAnimations(*this);
1437 imageChanged(&image);
1440 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1442 ASSERT(m_hasPausedImageAnimations);
1443 if (!shouldRepaintForImageAnimation(*this, visibleRect))
1449 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1451 auto* renderer = this;
1452 while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1453 renderer = renderer->parent();
1454 return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1457 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1459 return controlStatesRendererMap().contains(o);
1462 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1464 return controlStatesRendererMap().get(o);
1467 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1469 ControlStates* states = controlStatesRendererMap().get(o);
1471 controlStatesRendererMap().remove(o);
1476 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1478 controlStatesRendererMap().add(o, states);
1481 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1483 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1486 RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1490 RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1492 return style().addCachedPseudoStyle(result.release());
1496 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1498 if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1503 parentStyle = &style();
1509 if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1510 RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element(), parentStyle, DisallowStyleSharing);
1511 result->setStyleType(FIRST_LINE_INHERITED);
1512 return result.release();
1515 return document().ensureStyleResolver().pseudoStyleForElement(element(), pseudoStyleRequest, parentStyle);
1518 RenderBlock* RenderElement::containingBlockForFixedPosition() const
1520 const RenderElement* object = this;
1521 while (object && !object->canContainFixedPositionObjects())
1522 object = object->parent();
1524 ASSERT(!object || !object->isAnonymousBlock());
1525 return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1528 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
1530 const RenderElement* object = this;
1531 while (object && !object->canContainAbsolutelyPositionedObjects())
1532 object = object->parent();
1534 // For a relatively positioned inline, return its nearest non-anonymous containing block,
1535 // not the inline itself, to avoid having a positioned objects list in all RenderInlines
1536 // and use RenderBlock* as RenderElement::containingBlock's return type.
1537 // Use RenderBlock::container() to obtain the inline.
1538 if (object && !is<RenderBlock>(*object))
1539 object = object->containingBlock();
1541 while (object && object->isAnonymousBlock())
1542 object = object->containingBlock();
1544 return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1547 static inline bool isNonRenderBlockInline(const RenderElement& object)
1549 return (object.isInline() && !object.isReplaced()) || !object.isRenderBlock();
1552 RenderBlock* RenderElement::containingBlockForObjectInFlow() const
1554 const RenderElement* object = this;
1555 while (object && isNonRenderBlockInline(*object))
1556 object = object->parent();
1557 return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1560 Color RenderElement::selectionColor(int colorProperty) const
1562 // If the element is unselectable, or we are only painting the selection,
1563 // don't override the foreground color with the selection foreground color.
1564 if (style().userSelect() == SELECT_NONE
1565 || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1568 if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1569 Color color = pseudoStyle->visitedDependentColor(colorProperty);
1570 if (!color.isValid())
1571 color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1575 if (frame().selection().isFocusedAndActive())
1576 return theme().activeSelectionForegroundColor();
1577 return theme().inactiveSelectionForegroundColor();
1580 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1585 if (ShadowRoot* root = element()->containingShadowRoot()) {
1586 if (root->type() == ShadowRoot::UserAgentShadowRoot) {
1587 if (Element* shadowHost = element()->shadowHost())
1588 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1592 return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1595 Color RenderElement::selectionForegroundColor() const
1597 return selectionColor(CSSPropertyWebkitTextFillColor);
1600 Color RenderElement::selectionEmphasisMarkColor() const
1602 return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1605 Color RenderElement::selectionBackgroundColor() const
1607 if (style().userSelect() == SELECT_NONE)
1610 if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1611 return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1613 RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1614 if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1615 return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1617 if (frame().selection().isFocusedAndActive())
1618 return theme().activeSelectionBackgroundColor();
1619 return theme().inactiveSelectionBackgroundColor();
1622 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1624 if (!isInline() || isReplaced()) {
1625 point = localToAbsolute(FloatPoint(), UseTransforms);
1629 // find the next text/image child, to get a position
1630 const RenderObject* o = this;
1632 const RenderObject* p = o;
1633 if (RenderObject* child = o->firstChildSlow())
1635 else if (o->nextSibling())
1636 o = o->nextSibling();
1638 RenderObject* next = 0;
1639 while (!next && o->parent()) {
1641 next = o->nextSibling();
1650 if (!o->isInline() || o->isReplaced()) {
1651 point = o->localToAbsolute(FloatPoint(), UseTransforms);
1655 if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1656 // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1657 } else if (is<RenderText>(*o) || o->isReplaced()) {
1658 point = FloatPoint();
1659 if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1660 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1661 else if (is<RenderBox>(*o))
1662 point.moveBy(downcast<RenderBox>(*o).location());
1663 point = o->container()->localToAbsolute(point, UseTransforms);
1668 // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1669 // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1670 if (!o && document().view()) {
1671 point = FloatPoint(0, document().view()->contentsHeight());
1677 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1679 if (!isInline() || isReplaced()) {
1680 point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1684 // find the last text/image child, to get a position
1685 const RenderObject* o = this;
1687 if (RenderObject* child = o->lastChildSlow())
1689 else if (o->previousSibling())
1690 o = o->previousSibling();
1692 RenderObject* prev = 0;
1697 prev = o->previousSibling();
1702 if (is<RenderText>(*o) || o->isReplaced()) {
1703 point = FloatPoint();
1704 if (is<RenderText>(*o)) {
1705 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1706 if (!linesBox.maxX() && !linesBox.maxY())
1708 point.moveBy(linesBox.maxXMaxYCorner());
1710 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1711 point = o->container()->localToAbsolute(point, UseTransforms);
1718 LayoutRect RenderElement::anchorRect() const
1720 FloatPoint leading, trailing;
1721 bool foundLeading = getLeadingCorner(leading);
1722 bool foundTrailing = getTrailingCorner(trailing);
1724 // If we've found one corner, but not the other,
1725 // then we should just return a point at the corner that we did find.
1726 if (foundLeading != foundTrailing) {
1728 foundTrailing = foundLeading;
1730 foundLeading = foundTrailing;
1733 FloatPoint upperLeft = leading;
1734 FloatPoint lowerRight = trailing;
1736 // Vertical writing modes might mean the leading point is not in the top left
1737 if (!isInline() || isReplaced()) {
1738 upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1739 lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1740 } // Otherwise, it's not obvious what to do.
1742 return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1745 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1747 const RenderElement* current = this;
1749 if (current->isRenderBlock())
1751 if (!current->isRenderInline() || current->isRubyText())
1754 const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1755 if (styleToUse.textDecoration() & textDecoration)
1757 current = current->parent();
1758 } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));