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