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