Move continuation teardown from subclasses to RenderBoxModelObject.
[WebKit-https.git] / Source / WebCore / rendering / RenderElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013 Apple Inc. All rights reserved.
7  * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
8  *
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.
13  *
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.
18  *
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.
23  */
24
25 #include "config.h"
26 #include "RenderElement.h"
27
28 #include "AXObjectCache.h"
29 #include "ContentData.h"
30 #include "ControlStates.h"
31 #include "CursorList.h"
32 #include "EventHandler.h"
33 #include "Frame.h"
34 #include "FrameSelection.h"
35 #include "HTMLElement.h"
36 #include "HTMLNames.h"
37 #include "FlowThreadController.h"
38 #include "RenderCounter.h"
39 #include "RenderDeprecatedFlexibleBox.h"
40 #include "RenderFlexibleBox.h"
41 #include "RenderImage.h"
42 #include "RenderImageResourceStyleImage.h"
43 #include "RenderIterator.h"
44 #include "RenderLayer.h"
45 #include "RenderLayerCompositor.h"
46 #include "RenderLineBreak.h"
47 #include "RenderListItem.h"
48 #include "RenderNamedFlowThread.h"
49 #include "RenderRegion.h"
50 #include "RenderRuby.h"
51 #include "RenderRubyText.h"
52 #include "RenderTableCaption.h"
53 #include "RenderTableCell.h"
54 #include "RenderTableCol.h"
55 #include "RenderTableRow.h"
56 #include "RenderText.h"
57 #include "RenderTheme.h"
58 #include "RenderView.h"
59 #include "SVGRenderSupport.h"
60 #include "Settings.h"
61 #include "StyleResolver.h"
62 #include <wtf/MathExtras.h>
63 #include <wtf/StackStats.h>
64
65 #if ENABLE(CSS_GRID_LAYOUT)
66 #include "RenderGrid.h"
67 #endif
68
69 namespace WebCore {
70
71 bool RenderElement::s_affectsParentBlock = false;
72 bool RenderElement::s_noLongerAffectsParentBlock = false;
73     
74 static HashMap<const RenderObject*, ControlStates*>& controlStatesRendererMap()
75 {
76     static NeverDestroyed<HashMap<const RenderObject*, ControlStates*>> map;
77     return map;
78 }
79
80 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, PassRef<RenderStyle> style, unsigned baseTypeFlags)
81     : RenderObject(elementOrDocument)
82     , m_baseTypeFlags(baseTypeFlags)
83     , m_ancestorLineBoxDirty(false)
84     , m_hasInitializedStyle(false)
85     , m_renderInlineAlwaysCreatesLineBoxes(false)
86     , m_renderBoxNeedsLazyRepaint(false)
87     , m_hasPausedImageAnimations(false)
88     , m_hasCounterNodeMap(false)
89     , m_isCSSAnimating(false)
90     , m_hasContinuation(false)
91     , m_firstChild(nullptr)
92     , m_lastChild(nullptr)
93     , m_style(WTF::move(style))
94 {
95 }
96
97 RenderElement::RenderElement(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags)
98     : RenderElement(static_cast<ContainerNode&>(element), WTF::move(style), baseTypeFlags)
99 {
100 }
101
102 RenderElement::RenderElement(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags)
103     : RenderElement(static_cast<ContainerNode&>(document), WTF::move(style), baseTypeFlags)
104 {
105 }
106
107 RenderElement::~RenderElement()
108 {
109     if (hasInitializedStyle()) {
110         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
111             if (StyleImage* backgroundImage = bgLayer->image())
112                 backgroundImage->removeClient(this);
113         }
114
115         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
116             if (StyleImage* maskImage = maskLayer->image())
117                 maskImage->removeClient(this);
118         }
119
120         if (StyleImage* borderImage = m_style->borderImage().image())
121             borderImage->removeClient(this);
122
123         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
124             maskBoxImage->removeClient(this);
125
126 #if ENABLE(CSS_SHAPES)
127         if (auto shapeValue = m_style->shapeOutside()) {
128             if (auto shapeImage = shapeValue->image())
129                 shapeImage->removeClient(this);
130         }
131 #endif
132     }
133     if (m_hasPausedImageAnimations)
134         view().removeRendererWithPausedImageAnimations(*this);
135 }
136
137 RenderPtr<RenderElement> RenderElement::createFor(Element& element, PassRef<RenderStyle> style)
138 {
139     // Minimal support for content properties replacing an entire element.
140     // Works only if we have exactly one piece of content and it's a URL.
141     // Otherwise acts as if we didn't support this feature.
142     const ContentData* contentData = style.get().contentData();
143     if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
144         auto& styleImage = downcast<ImageContentData>(*contentData).image();
145         auto image = createRenderer<RenderImage>(element, WTF::move(style), const_cast<StyleImage*>(&styleImage));
146         image->setIsGeneratedContent();
147         return WTF::move(image);
148     }
149
150     if (element.hasTagName(HTMLNames::rubyTag)) {
151         if (style.get().display() == INLINE)
152             return createRenderer<RenderRubyAsInline>(element, WTF::move(style));
153         if (style.get().display() == BLOCK)
154             return createRenderer<RenderRubyAsBlock>(element, WTF::move(style));
155     }
156     // treat <rt> as ruby text ONLY if it still has its default treatment of block
157     if (element.hasTagName(HTMLNames::rtTag) && style.get().display() == BLOCK)
158         return createRenderer<RenderRubyText>(element, WTF::move(style));
159     switch (style.get().display()) {
160     case NONE:
161         style.dropRef();
162         return nullptr;
163     case INLINE:
164         return createRenderer<RenderInline>(element, WTF::move(style));
165     case BLOCK:
166     case INLINE_BLOCK:
167     case COMPACT:
168         return createRenderer<RenderBlockFlow>(element, WTF::move(style));
169     case LIST_ITEM:
170         return createRenderer<RenderListItem>(element, WTF::move(style));
171     case TABLE:
172     case INLINE_TABLE:
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));
178     case TABLE_ROW:
179         return createRenderer<RenderTableRow>(element, WTF::move(style));
180     case TABLE_COLUMN_GROUP:
181     case TABLE_COLUMN:
182         return createRenderer<RenderTableCol>(element, WTF::move(style));
183     case TABLE_CELL:
184         return createRenderer<RenderTableCell>(element, WTF::move(style));
185     case TABLE_CAPTION:
186         return createRenderer<RenderTableCaption>(element, WTF::move(style));
187     case BOX:
188     case INLINE_BOX:
189         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTF::move(style));
190     case FLEX:
191     case INLINE_FLEX:
192     case WEBKIT_FLEX:
193     case WEBKIT_INLINE_FLEX:
194         return createRenderer<RenderFlexibleBox>(element, WTF::move(style));
195 #if ENABLE(CSS_GRID_LAYOUT)
196     case GRID:
197     case INLINE_GRID:
198         return createRenderer<RenderGrid>(element, WTF::move(style));
199 #endif
200     }
201     ASSERT_NOT_REACHED();
202     return nullptr;
203 }
204
205 enum StyleCacheState {
206     Cached,
207     Uncached
208 };
209
210 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderElement& renderer, RenderStyle* style)
211 {
212     RenderElement& rendererForFirstLineStyle = renderer.isBeforeOrAfterContent() ? *renderer.parent() : const_cast<RenderElement&>(renderer);
213
214     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
215         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock()) {
216             if (type == Cached)
217                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
218             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == &renderer ? style : nullptr);
219         }
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);
227             }
228             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
229         }
230     }
231     return nullptr;
232 }
233
234 PassRefPtr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
235 {
236     if (!document().styleSheetCollection().usesFirstLineRules())
237         return nullptr;
238
239     return firstLineStyleForCachedUncachedType(Uncached, *this, style);
240 }
241
242 RenderStyle* RenderElement::cachedFirstLineStyle() const
243 {
244     ASSERT(document().styleSheetCollection().usesFirstLineRules());
245
246     RenderStyle& style = this->style();
247     if (RefPtr<RenderStyle> firstLineStyle = firstLineStyleForCachedUncachedType(Cached, *this, &style))
248         return firstLineStyle.get();
249
250     return &style;
251 }
252
253 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
254 {
255     // If transform changed, and we are not composited, need to do a layout.
256     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
257         // Text nodes share style with their parents but transforms don't apply to them,
258         // hence the !isText() check.
259         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
260         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
261             // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
262             // then we actually need SimplifiedLayoutAndPositionedMovement.
263             if (!hasLayer())
264                 diff = StyleDifferenceLayout; // FIXME: Do this for now since SimplifiedLayout cannot handle updating floating objects lists.
265             else if (diff < StyleDifferenceLayoutPositionedMovementOnly)
266                 diff = StyleDifferenceSimplifiedLayout;
267             else if (diff < StyleDifferenceSimplifiedLayout)
268                 diff = StyleDifferenceSimplifiedLayoutAndPositionedMovement;
269         } else if (diff < StyleDifferenceRecompositeLayer)
270             diff = StyleDifferenceRecompositeLayer;
271     }
272
273     // If opacity changed, and we are not composited, need to repaint (also
274     // ignoring text nodes)
275     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
276         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
277             diff = StyleDifferenceRepaintLayer;
278         else if (diff < StyleDifferenceRecompositeLayer)
279             diff = StyleDifferenceRecompositeLayer;
280     }
281
282     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
283         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
284         if (!layer->isComposited() || layer->paintsWithFilters())
285             diff = StyleDifferenceRepaintLayer;
286         else if (diff < StyleDifferenceRecompositeLayer)
287             diff = StyleDifferenceRecompositeLayer;
288     }
289     
290     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
291     // style changing, since it depends on whether we decide to composite these elements. When the
292     // layer status of one of these elements changes, we need to force a layout.
293     if (diff == StyleDifferenceEqual && isRenderLayerModelObject()) {
294         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
295             diff = StyleDifferenceLayout;
296     }
297
298     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
299     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
300         diff = StyleDifferenceRepaint;
301
302     return diff;
303 }
304
305 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
306 {
307     for (auto& child : childrenOfType<RenderObject>(*this)) {
308         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
309             return true;
310         if (child.style().hasOutline() || child.style().hasBorder())
311             return true;
312     }
313     return false;
314 }
315
316 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
317 {
318     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
319 }
320
321 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
322 {
323     // Optimize the common case
324     if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
325         return;
326     
327     // Go through the new layers and addClients first, to avoid removing all clients of an image.
328     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
329         if (currNew->image())
330             currNew->image()->addClient(this);
331     }
332
333     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
334         if (currOld->image())
335             currOld->image()->removeClient(this);
336     }
337 }
338
339 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
340 {
341     if (oldImage == newImage)
342         return;
343     if (oldImage)
344         oldImage->removeClient(this);
345     if (newImage)
346         newImage->addClient(this);
347 }
348
349 #if ENABLE(CSS_SHAPES)
350 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
351 {
352     if (oldShapeValue || newShapeValue)
353         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
354 }
355 #endif
356
357 void RenderElement::initializeStyle()
358 {
359     styleWillChange(StyleDifferenceEqual, style());
360
361     m_hasInitializedStyle = true;
362
363     updateFillImages(nullptr, m_style->backgroundLayers());
364     updateFillImages(nullptr, m_style->maskLayers());
365
366     updateImage(nullptr, m_style->borderImage().image());
367     updateImage(nullptr, m_style->maskBoxImage().image());
368
369 #if ENABLE(CSS_SHAPES)
370     updateShapeImage(nullptr, m_style->shapeOutside());
371 #endif
372
373     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
374     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
375     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
376         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
377
378     styleDidChange(StyleDifferenceEqual, nullptr);
379
380     // We shouldn't have any text children that would need styleDidChange at this point.
381     ASSERT(!childrenOfType<RenderText>(*this).first());
382
383     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
384     // have their parent set before getting a call to initializeStyle() :|
385 }
386
387 void RenderElement::setStyle(PassRef<RenderStyle> style)
388 {
389     // FIXME: Should change RenderView so it can use initializeStyle too.
390     // If we do that, we can assert m_hasInitializedStyle unconditionally,
391     // and remove the check of m_hasInitializedStyle below too.
392     ASSERT(m_hasInitializedStyle || isRenderView());
393
394     if (&m_style.get() == &style.get()) {
395         // FIXME: Can we change things so we never hit this code path?
396         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
397         // style sharing is disabled for them. That should ensure that we never hit this code path.
398         ASSERT(!isRenderIFrame());
399         ASSERT(!isEmbeddedObject());
400         ASSERT(!isCanvas());
401         style.dropRef();
402         return;
403     }
404
405     StyleDifference diff = StyleDifferenceEqual;
406     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
407     if (m_hasInitializedStyle)
408         diff = m_style->diff(&style.get(), contextSensitiveProperties);
409
410     diff = adjustStyleDifference(diff, contextSensitiveProperties);
411
412     styleWillChange(diff, style.get());
413
414     Ref<RenderStyle> oldStyle(m_style.replace(WTF::move(style)));
415
416     updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
417     updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
418
419     updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
420     updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
421
422 #if ENABLE(CSS_SHAPES)
423     updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
424 #endif
425
426     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
427     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
428     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
429         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
430
431     bool doesNotNeedLayout = !parent();
432
433     styleDidChange(diff, &oldStyle.get());
434
435     // Text renderers use their parent style. Notify them about the change.
436     for (auto& child : childrenOfType<RenderText>(*this))
437         child.styleDidChange(diff, &oldStyle.get());
438
439     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
440     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
441     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
442     // in the future as we move renderer changes out of layout and into style changes.
443     if (doesNotNeedLayout)
444         return;
445
446     // Now that the layer (if any) has been updated, we need to adjust the diff again,
447     // check whether we should layout now, and decide if we need to repaint.
448     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
449     
450     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
451         if (updatedDiff == StyleDifferenceLayout)
452             setNeedsLayoutAndPrefWidthsRecalc();
453         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
454             setNeedsPositionedMovementLayout(&oldStyle.get());
455         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
456             setNeedsPositionedMovementLayout(&oldStyle.get());
457             setNeedsSimplifiedNormalFlowLayout();
458         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
459             setNeedsSimplifiedNormalFlowLayout();
460     }
461
462     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
463         // Do a repaint with the new style now, e.g., for example if we go from
464         // not having an outline to having an outline.
465         repaint();
466     }
467 }
468
469 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
470 {
471     bool needsTable = false;
472
473     if (is<RenderTableCol>(*newChild)) {
474         RenderTableCol& newTableColumn = downcast<RenderTableCol>(*newChild);
475         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
476         needsTable = !is<RenderTable>(*this) && !isColumnInColumnGroup;
477     } else if (is<RenderTableCaption>(*newChild))
478         needsTable = !is<RenderTable>(*this);
479     else if (is<RenderTableSection>(*newChild))
480         needsTable = !is<RenderTable>(*this);
481     else if (is<RenderTableRow>(*newChild))
482         needsTable = !is<RenderTableSection>(*this);
483     else if (is<RenderTableCell>(*newChild))
484         needsTable = !is<RenderTableRow>(*this);
485
486     if (needsTable) {
487         RenderTable* table;
488         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
489         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
490             table = downcast<RenderTable>(afterChild);
491         else {
492             table = RenderTable::createAnonymousWithParentRenderer(this);
493             addChild(table, beforeChild);
494         }
495         table->addChild(newChild);
496     } else
497         insertChildInternal(newChild, beforeChild, NotifyChildren);
498
499     if (is<RenderText>(*newChild))
500         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
501
502     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
503     // <g>s to have renderers - at least that's how our implementation works. Consider:
504     // <g display="none"><foreignObject><body style="position: relative">FOO...
505     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
506     // - when the document is painted, both layers are painted. The <body> layer doesn't
507     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
508     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
509     // and stop creating layers at all for these cases - they're not used anyways.
510     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
511         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
512
513     SVGRenderSupport::childAdded(*this, *newChild);
514 }
515
516 RenderObject* RenderElement::removeChild(RenderObject& oldChild)
517 {
518     return removeChildInternal(oldChild, NotifyChildren);
519 }
520
521 void RenderElement::destroyLeftoverChildren()
522 {
523     while (m_firstChild) {
524         if (m_firstChild->isListMarker() || (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText())) {
525             m_firstChild->removeFromParent(); // List markers are owned by their enclosing list and so don't get destroyed by this container. Similarly, first letters are destroyed by their remaining text fragment.
526         } else {
527             // 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.
528             if (m_firstChild->node())
529                 m_firstChild->node()->setRenderer(nullptr);
530             m_firstChild->destroy();
531         }
532     }
533 }
534
535 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
536 {
537     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
538     ASSERT(!newChild->parent());
539     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
540
541     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
542         beforeChild = beforeChild->parent();
543
544     // This should never happen, but if it does prevent render tree corruption
545     // where child->parent() ends up being owner but child->nextSibling()->parent()
546     // is not owner.
547     if (beforeChild && beforeChild->parent() != this) {
548         ASSERT_NOT_REACHED();
549         return;
550     }
551
552     newChild->setParent(this);
553
554     if (m_firstChild == beforeChild)
555         m_firstChild = newChild;
556
557     if (beforeChild) {
558         RenderObject* previousSibling = beforeChild->previousSibling();
559         if (previousSibling)
560             previousSibling->setNextSibling(newChild);
561         newChild->setPreviousSibling(previousSibling);
562         newChild->setNextSibling(beforeChild);
563         beforeChild->setPreviousSibling(newChild);
564     } else {
565         if (lastChild())
566             lastChild()->setNextSibling(newChild);
567         newChild->setPreviousSibling(lastChild());
568         m_lastChild = newChild;
569     }
570
571     if (!documentBeingDestroyed()) {
572         if (notifyChildren == NotifyChildren)
573             newChild->insertedIntoTree();
574         if (is<RenderElement>(*newChild))
575             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
576     }
577
578     newChild->setNeedsLayoutAndPrefWidthsRecalc();
579     setPreferredLogicalWidthsDirty(true);
580     if (!normalChildNeedsLayout())
581         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
582
583     if (AXObjectCache* cache = document().axObjectCache())
584         cache->childrenChanged(this, newChild);
585 }
586
587 RenderObject* RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
588 {
589     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
590     ASSERT(oldChild.parent() == this);
591
592     if (oldChild.isFloatingOrOutOfFlowPositioned())
593         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
594
595     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
596     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
597     // disappears gets repainted properly.
598     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
599         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
600         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
601         if (oldChild.isBody())
602             view().repaintRootContents();
603         else
604             oldChild.repaint();
605     }
606
607     // If we have a line box wrapper, delete it.
608     if (is<RenderBox>(oldChild))
609         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
610     else if (is<RenderLineBreak>(oldChild))
611         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
612
613     // If oldChild is the start or end of the selection, then clear the selection to
614     // avoid problems of invalid pointers.
615     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
616         frame().selection().setNeedsSelectionUpdate();
617
618     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
619         oldChild.willBeRemovedFromTree();
620
621     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
622     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
623     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
624     
625     RenderObject* nextSibling = oldChild.nextSibling();
626
627     if (oldChild.previousSibling())
628         oldChild.previousSibling()->setNextSibling(nextSibling);
629     if (nextSibling)
630         nextSibling->setPreviousSibling(oldChild.previousSibling());
631
632     if (m_firstChild == &oldChild)
633         m_firstChild = nextSibling;
634     if (m_lastChild == &oldChild)
635         m_lastChild = oldChild.previousSibling();
636
637     oldChild.setPreviousSibling(nullptr);
638     oldChild.setNextSibling(nullptr);
639     oldChild.setParent(nullptr);
640
641     // rendererRemovedFromTree walks the whole subtree. We can improve performance
642     // by skipping this step when destroying the entire tree.
643     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
644         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
645
646     if (AXObjectCache* cache = document().existingAXObjectCache())
647         cache->childrenChanged(this);
648     
649     return nextSibling;
650 }
651
652 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
653 {
654     if (renderer.hasLayer()) {
655         if (!beforeChild && newObject) {
656             // We need to figure out the layer that follows newObject. We only do
657             // this the first time we find a child layer, and then we update the
658             // pointer values for newObject and beforeChild used by everyone else.
659             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
660             newObject = nullptr;
661         }
662         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
663         return;
664     }
665
666     for (auto& child : childrenOfType<RenderElement>(renderer))
667         addLayers(child, parentLayer, newObject, beforeChild);
668 }
669
670 void RenderElement::addLayers(RenderLayer* parentLayer)
671 {
672     if (!parentLayer)
673         return;
674
675     RenderElement* renderer = this;
676     RenderLayer* beforeChild = nullptr;
677     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
678 }
679
680 void RenderElement::removeLayers(RenderLayer* parentLayer)
681 {
682     if (!parentLayer)
683         return;
684
685     if (hasLayer()) {
686         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
687         return;
688     }
689
690     for (auto& child : childrenOfType<RenderElement>(*this))
691         child.removeLayers(parentLayer);
692 }
693
694 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
695 {
696     if (!newParent)
697         return;
698
699     if (hasLayer()) {
700         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
701         ASSERT(oldParent == layer->parent());
702         if (oldParent)
703             oldParent->removeChild(layer);
704         newParent->addChild(layer);
705         return;
706     }
707
708     for (auto& child : childrenOfType<RenderElement>(*this))
709         child.moveLayers(oldParent, newParent);
710 }
711
712 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
713 {
714     // Error check the parent layer passed in. If it's null, we can't find anything.
715     if (!parentLayer)
716         return nullptr;
717
718     // Step 1: If our layer is a child of the desired parent, then return our layer.
719     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
720     if (ourLayer && ourLayer->parent() == parentLayer)
721         return ourLayer;
722
723     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
724     // into our siblings trying to find the next layer whose parent is the desired parent.
725     if (!ourLayer || ourLayer == parentLayer) {
726         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
727             if (!is<RenderElement>(*child))
728                 continue;
729             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
730             if (nextLayer)
731                 return nextLayer;
732         }
733     }
734
735     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
736     // find anything.
737     if (parentLayer == ourLayer)
738         return nullptr;
739
740     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
741     // follow us to see if we can locate a layer.
742     if (checkParent && parent())
743         return parent()->findNextLayer(parentLayer, this, true);
744
745     return nullptr;
746 }
747
748 bool RenderElement::layerCreationAllowedForSubtree() const
749 {
750     RenderElement* parentRenderer = parent();
751     while (parentRenderer) {
752         if (parentRenderer->isSVGHiddenContainer())
753             return false;
754         parentRenderer = parentRenderer->parent();
755     }
756     
757     return true;
758 }
759
760 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
761 {
762     // FIXME: We could save this call when the change only affected non-inherited properties.
763     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
764         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
765             continue;
766
767         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
768             continue;
769
770 #if ENABLE(FULLSCREEN_API)
771         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
772             continue;
773 #endif
774
775         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
776         if (is<RenderFlowThread>(elementChild))
777             continue;
778
779         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
780         if (style().specifiesColumns()) {
781             if (elementChild.style().specifiesColumns())
782                 newStyle.get().inheritColumnPropertiesFrom(&style());
783             if (elementChild.style().columnSpan())
784                 newStyle.get().setColumnSpan(ColumnSpanAll);
785         }
786
787         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
788         // they contain block descendants of relative or sticky positioned inlines.
789         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
790             newStyle.get().setPosition(elementChild.style().position());
791
792         elementChild.setStyle(WTF::move(newStyle));
793     }
794 }
795
796 static inline bool rendererHasBackground(const RenderElement* renderer)
797 {
798     return renderer && renderer->hasBackground();
799 }
800
801 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
802 {
803     RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
804     if (oldStyle) {
805         // If our z-index changes value or our visibility changes,
806         // we need to dirty our stacking context's z-order list.
807         bool visibilityChanged = m_style->visibility() != newStyle.visibility()
808             || m_style->zIndex() != newStyle.zIndex()
809             || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
810 #if ENABLE(DASHBOARD_SUPPORT)
811         if (visibilityChanged)
812             document().setAnnotatedRegionsDirty(true);
813 #endif
814 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
815         if (visibilityChanged)
816             document().dirtyTouchEventRects();
817 #endif
818         if (visibilityChanged) {
819             if (AXObjectCache* cache = document().existingAXObjectCache())
820                 cache->childrenChanged(parent(), this);
821         }
822
823         // Keep layer hierarchy visibility bits up to date if visibility changes.
824         if (m_style->visibility() != newStyle.visibility()) {
825             if (RenderLayer* layer = enclosingLayer()) {
826                 if (newStyle.visibility() == VISIBLE)
827                     layer->setHasVisibleContent();
828                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
829                     layer->dirtyVisibleContentStatus();
830                     if (diff > StyleDifferenceRepaintLayer)
831                         repaint();
832                 }
833             }
834         }
835
836         if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
837             repaint();
838         if (isFloating() && (m_style->floating() != newStyle.floating()))
839             // For changes in float styles, we need to conceivably remove ourselves
840             // from the floating objects list.
841             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
842         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
843             // For changes in positioning styles, we need to conceivably remove ourselves
844             // from the positioned objects list.
845             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
846
847         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
848             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
849             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
850
851         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
852             && parent() && parent()->isRenderBlock();
853
854         // reset style flags
855         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
856             setFloating(false);
857             clearPositionedState();
858         }
859         setHorizontalWritingMode(true);
860         setHasBoxDecorations(false);
861         setHasOverflowClip(false);
862         setHasTransform(false);
863         setHasReflection(false);
864     } else {
865         s_affectsParentBlock = false;
866         s_noLongerAffectsParentBlock = false;
867     }
868
869     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
870     bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
871     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
872         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
873
874         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
875         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
876         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
877         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
878             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
879                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
880                     newStyleSlowScroll = false;
881
882                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
883                     oldStyleSlowScroll = false;
884             }
885         }
886
887         if (oldStyleSlowScroll != newStyleSlowScroll) {
888             if (oldStyleSlowScroll)
889                 view().frameView().removeSlowRepaintObject(this);
890
891             if (newStyleSlowScroll)
892                 view().frameView().addSlowRepaintObject(this);
893         }
894     }
895
896     if (isRoot() || isBody())
897         view().frameView().updateExtendBackgroundIfNecessary();
898 }
899
900 #if !PLATFORM(IOS)
901 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
902 {
903     ASSERT(a->cursors() != b->cursors());
904     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
905 }
906
907 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
908 {
909     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
910 }
911 #endif
912
913 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
914 {
915     if (s_affectsParentBlock)
916         handleDynamicFloatPositionChange();
917
918     if (s_noLongerAffectsParentBlock)
919         removeAnonymousWrappersForInlinesIfNecessary();
920
921     SVGRenderSupport::styleChanged(*this, oldStyle);
922
923     if (!m_parent)
924         return;
925     
926     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
927         RenderCounter::rendererStyleChanged(*this, oldStyle, &m_style.get());
928
929         // If the object already needs layout, then setNeedsLayout won't do
930         // any work. But if the containing block has changed, then we may need
931         // to mark the new containing blocks for layout. The change that can
932         // directly affect the containing block of this object is a change to
933         // the position style.
934         if (needsLayout() && oldStyle->position() != m_style->position())
935             markContainingBlocksForLayout();
936
937         if (diff == StyleDifferenceLayout)
938             setNeedsLayoutAndPrefWidthsRecalc();
939         else
940             setNeedsSimplifiedNormalFlowLayout();
941     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
942         setNeedsPositionedMovementLayout(oldStyle);
943         setNeedsSimplifiedNormalFlowLayout();
944     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
945         setNeedsPositionedMovementLayout(oldStyle);
946
947     // Don't check for repaint here; we need to wait until the layer has been
948     // updated by subclasses before we know if we have to repaint (in setStyle()).
949
950 #if !PLATFORM(IOS)
951     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
952         frame().eventHandler().scheduleCursorUpdate();
953 #endif
954 }
955
956 void RenderElement::insertedIntoTree()
957 {
958     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
959         containerFlowThread->addFlowChild(*this);
960
961     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
962     // and don't have a layer attached to ourselves.
963     RenderLayer* layer = nullptr;
964     if (firstChild() || hasLayer()) {
965         layer = parent()->enclosingLayer();
966         addLayers(layer);
967     }
968
969     // If |this| is visible but this object was not, tell the layer it has some visible content
970     // that needs to be drawn and layer visibility optimization can't be used
971     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
972         if (!layer)
973             layer = parent()->enclosingLayer();
974         if (layer)
975             layer->setHasVisibleContent();
976     }
977
978     RenderObject::insertedIntoTree();
979 }
980
981 void RenderElement::willBeRemovedFromTree()
982 {
983     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
984     RenderLayer* layer = nullptr;
985     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
986         if ((layer = parent()->enclosingLayer()))
987             layer->dirtyVisibleContentStatus();
988     }
989     // Keep our layer hierarchy updated.
990     if (firstChild() || hasLayer()) {
991         if (!layer)
992             layer = parent()->enclosingLayer();
993         removeLayers(layer);
994     }
995
996     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
997         view().frameView().removeSlowRepaintObject(this);
998
999     if (isOutOfFlowPositioned() && parent()->childrenInline())
1000         parent()->dirtyLinesFromChangedChild(*this);
1001
1002     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1003         containerFlowThread->removeFlowChild(*this);
1004
1005     RenderObject::willBeRemovedFromTree();
1006 }
1007
1008 void RenderElement::willBeDestroyed()
1009 {
1010     animation().cancelAnimations(*this);
1011
1012     destroyLeftoverChildren();
1013
1014     if (hasCounterNodeMap())
1015         RenderCounter::destroyCounterNodes(*this);
1016
1017     RenderObject::willBeDestroyed();
1018
1019 #if !ASSERT_DISABLED
1020     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1021         // After remove, the object and the associated information should not be in any flow thread.
1022         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1023             ASSERT(!flowThread->hasChild(*this));
1024             ASSERT(!flowThread->hasChildInfo(this));
1025         }
1026     }
1027 #endif
1028 }
1029
1030 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1031 {
1032     ASSERT(!isSetNeedsLayoutForbidden());
1033     if (needsPositionedMovementLayout())
1034         return;
1035     setNeedsPositionedMovementLayoutBit(true);
1036     markContainingBlocksForLayout();
1037     if (hasLayer()) {
1038         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1039             setLayerNeedsFullRepaint();
1040         else
1041             setLayerNeedsFullRepaintForPositionedMovementLayout();
1042     }
1043 }
1044
1045 void RenderElement::clearChildNeedsLayout()
1046 {
1047     setNormalChildNeedsLayoutBit(false);
1048     setPosChildNeedsLayoutBit(false);
1049     setNeedsSimplifiedNormalFlowLayoutBit(false);
1050     setNormalChildNeedsLayoutBit(false);
1051     setNeedsPositionedMovementLayoutBit(false);
1052 }
1053
1054 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1055 {
1056     ASSERT(!isSetNeedsLayoutForbidden());
1057     if (needsSimplifiedNormalFlowLayout())
1058         return;
1059     setNeedsSimplifiedNormalFlowLayoutBit(true);
1060     markContainingBlocksForLayout();
1061     if (hasLayer())
1062         setLayerNeedsFullRepaint();
1063 }
1064
1065 RenderElement& RenderElement::rendererForRootBackground()
1066 {
1067     ASSERT(isRoot());
1068     if (!hasBackground() && element() && element()->hasTagName(HTMLNames::htmlTag)) {
1069         // Locate the <body> element using the DOM. This is easier than trying
1070         // to crawl around a render tree with potential :before/:after content and
1071         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1072         // render object very easily via the DOM.
1073         if (auto body = document().body()) {
1074             if (body->hasTagName(HTMLNames::bodyTag)) {
1075                 if (auto renderer = body->renderer())
1076                     return *renderer;
1077             }
1078         }
1079     }
1080     return *this;
1081 }
1082
1083 RenderElement* RenderElement::hoverAncestor() const
1084 {
1085     // When searching for the hover ancestor and encountering a named flow thread,
1086     // the search will continue with the DOM ancestor of the top-most element
1087     // in the named flow thread.
1088     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1089     RenderElement* hoverAncestor = parent();
1090
1091     // Skip anonymous blocks directly flowed into flow threads as it would
1092     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1093     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1094         hoverAncestor = hoverAncestor->parent();
1095
1096     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1097         hoverAncestor = nullptr;
1098         if (Element* element = this->element()) {
1099             if (auto parent = element->parentNode())
1100                 hoverAncestor = parent->renderer();
1101         }
1102     }
1103
1104     return hoverAncestor;
1105 }
1106
1107 void RenderElement::layout()
1108 {
1109     StackStats::LayoutCheckPoint layoutCheckPoint;
1110     ASSERT(needsLayout());
1111     RenderObject* child = firstChild();
1112     while (child) {
1113         if (child->needsLayout())
1114             downcast<RenderElement>(*child).layout();
1115         ASSERT(!child->needsLayout());
1116         child = child->nextSibling();
1117     }
1118     clearNeedsLayout();
1119 }
1120
1121 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1122 {
1123     // Nobody will use multiple layers without wanting fancy positioning.
1124     if (layer->next())
1125         return true;
1126
1127     // Make sure we have a valid image.
1128     StyleImage* image = layer->image();
1129     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1130         return false;
1131
1132     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1133         return true;
1134
1135     EFillSizeType sizeType = layer->sizeType();
1136
1137     if (sizeType == Contain || sizeType == Cover)
1138         return true;
1139
1140     if (sizeType == SizeLength) {
1141         LengthSize size = layer->sizeLength();
1142         if (size.width().isPercent() || size.height().isPercent())
1143             return true;
1144         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1145         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1146             return true;
1147     } else if (image->usesImageContainerSize())
1148         return true;
1149
1150     return false;
1151 }
1152
1153 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1154 {
1155     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1156         return true;
1157
1158     // If we don't have a background/border/mask, then nothing to do.
1159     if (!renderer.hasBoxDecorations())
1160         return false;
1161
1162     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1163         return true;
1164
1165     // Our fill layers are ok. Let's check border.
1166     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1167         return true;
1168
1169     return false;
1170 }
1171
1172 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1173 {
1174     if (view().printing())
1175         return false; // Don't repaint if we're printing.
1176
1177     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1178     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1179     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1180     LayoutRect newOutlineBox;
1181
1182     bool fullRepaint = selfNeedsLayout();
1183     // Presumably a background or a border exists if border-fit:lines was specified.
1184     if (!fullRepaint && style().borderFit() == BorderFitLines)
1185         fullRepaint = true;
1186     if (!fullRepaint) {
1187         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1188         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1189         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1190         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1191             fullRepaint = true;
1192     }
1193
1194     if (!repaintContainer)
1195         repaintContainer = &view();
1196
1197     if (fullRepaint) {
1198         repaintUsingContainer(repaintContainer, oldBounds);
1199         if (newBounds != oldBounds)
1200             repaintUsingContainer(repaintContainer, newBounds);
1201         return true;
1202     }
1203
1204     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1205         return false;
1206
1207     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1208     if (deltaLeft > 0)
1209         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1210     else if (deltaLeft < 0)
1211         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1212
1213     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1214     if (deltaRight > 0)
1215         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1216     else if (deltaRight < 0)
1217         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1218
1219     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1220     if (deltaTop > 0)
1221         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1222     else if (deltaTop < 0)
1223         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1224
1225     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1226     if (deltaBottom > 0)
1227         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1228     else if (deltaBottom < 0)
1229         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1230
1231     if (newOutlineBox == oldOutlineBox)
1232         return false;
1233
1234     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1235     // two rectangles (but typically only one).
1236     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1237     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1238     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1239     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1240     if (width) {
1241         LayoutUnit shadowLeft;
1242         LayoutUnit shadowRight;
1243         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1244         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1245         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1246         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1247         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1248         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1249         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1250             newOutlineBox.y(),
1251             width + decorationsWidth,
1252             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1253         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1254         if (rightRect.x() < right) {
1255             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1256             repaintUsingContainer(repaintContainer, rightRect);
1257         }
1258     }
1259     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1260     if (height) {
1261         LayoutUnit shadowTop;
1262         LayoutUnit shadowBottom;
1263         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1264         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1265         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1266         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1267         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1268             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1269         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1270         LayoutRect bottomRect(newOutlineBox.x(),
1271             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1272             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1273             height + decorationsHeight);
1274         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1275         if (bottomRect.y() < bottom) {
1276             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1277             repaintUsingContainer(repaintContainer, bottomRect);
1278         }
1279     }
1280     return false;
1281 }
1282
1283 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1284 {
1285     ASSERT(style().hasBorder());
1286
1287     StyleImage* borderImage = style().borderImage().image();
1288     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1289 }
1290
1291 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1292 {
1293     const Document& document = renderer.document();
1294     if (document.inPageCache())
1295         return false;
1296     auto& frameView = renderer.view().frameView();
1297     if (frameView.isOffscreen())
1298         return false;
1299 #if PLATFORM(IOS)
1300     if (document.frame()->timersPaused())
1301         return false;
1302 #endif
1303     if (document.activeDOMObjectsAreSuspended())
1304         return false;
1305     if (renderer.style().visibility() != VISIBLE)
1306         return false;
1307     if (!visibleRect.intersects(renderer.absoluteBoundingBoxRect()))
1308         return false;
1309
1310     return true;
1311 }
1312
1313 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1314 {
1315     auto& frameView = view().frameView();
1316     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1317     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1318         view().addRendererWithPausedImageAnimations(*this);
1319         return;
1320     }
1321     imageChanged(&image);
1322 }
1323
1324 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1325 {
1326     ASSERT(m_hasPausedImageAnimations);
1327     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1328         return false;
1329     repaint();
1330     return true;
1331 }
1332
1333 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1334 {
1335     auto* renderer = this;
1336     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1337         renderer = renderer->parent();
1338     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1339 }
1340
1341 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1342 {
1343     return controlStatesRendererMap().contains(o);
1344 }
1345
1346 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1347 {
1348     return controlStatesRendererMap().get(o);
1349 }
1350
1351 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1352 {
1353     ControlStates* states = controlStatesRendererMap().get(o);
1354     if (states) {
1355         controlStatesRendererMap().remove(o);
1356         delete states;
1357     }
1358 }
1359
1360 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1361 {
1362     controlStatesRendererMap().add(o, states);
1363 }
1364
1365 }