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