RenderElement::m_style should be a Ref.
[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 "RenderCounter.h"
37 #include "RenderDeprecatedFlexibleBox.h"
38 #include "RenderFlexibleBox.h"
39 #include "RenderGrid.h"
40 #include "RenderImage.h"
41 #include "RenderImageResourceStyleImage.h"
42 #include "RenderLayer.h"
43 #include "RenderLineBreak.h"
44 #include "RenderListItem.h"
45 #include "RenderMultiColumnBlock.h"
46 #include "RenderRegion.h"
47 #include "RenderRuby.h"
48 #include "RenderRubyText.h"
49 #include "RenderTableCaption.h"
50 #include "RenderTableCell.h"
51 #include "RenderTableCol.h"
52 #include "RenderTableRow.h"
53 #include "RenderText.h"
54 #include "RenderView.h"
55 #include "SVGRenderSupport.h"
56 #include "StyleResolver.h"
57 #include <wtf/StackStats.h>
58
59 #if USE(ACCELERATED_COMPOSITING)
60 #include "RenderLayerCompositor.h"
61 #endif
62
63 namespace WebCore {
64
65 bool RenderElement::s_affectsParentBlock = false;
66 bool RenderElement::s_noLongerAffectsParentBlock = false;
67
68 RenderElement::RenderElement(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags)
69     : RenderObject(element)
70     , m_baseTypeFlags(baseTypeFlags)
71     , m_ancestorLineBoxDirty(false)
72     , m_hasInitializedStyle(false)
73     , m_firstChild(nullptr)
74     , m_lastChild(nullptr)
75     , m_style(std::move(style))
76 {
77 }
78
79 RenderElement::RenderElement(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags)
80     : RenderObject(document)
81     , m_baseTypeFlags(baseTypeFlags)
82     , m_ancestorLineBoxDirty(false)
83     , m_hasInitializedStyle(false)
84     , m_firstChild(nullptr)
85     , m_lastChild(nullptr)
86     , m_style(std::move(style))
87 {
88 }
89
90 RenderElement::~RenderElement()
91 {
92     if (hasInitializedStyle()) {
93         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
94             if (StyleImage* backgroundImage = bgLayer->image())
95                 backgroundImage->removeClient(this);
96         }
97
98         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
99             if (StyleImage* maskImage = maskLayer->image())
100                 maskImage->removeClient(this);
101         }
102
103         if (StyleImage* borderImage = m_style->borderImage().image())
104             borderImage->removeClient(this);
105
106         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
107             maskBoxImage->removeClient(this);
108
109 #if ENABLE(CSS_SHAPES)
110         if (auto shapeValue = m_style->shapeInside()) {
111             if (auto shapeImage = shapeValue->image())
112                 shapeImage->removeClient(this);
113         }
114         if (auto shapeValue = m_style->shapeOutside()) {
115             if (auto shapeImage = shapeValue->image())
116                 shapeImage->removeClient(this);
117         }
118 #endif
119     }
120 }
121
122 RenderElement* RenderElement::createFor(Element& element, PassRef<RenderStyle> style)
123 {
124     Document& document = element.document();
125
126     // Minimal support for content properties replacing an entire element.
127     // Works only if we have exactly one piece of content and it's a URL.
128     // Otherwise acts as if we didn't support this feature.
129     const ContentData* contentData = style.get().contentData();
130     if (contentData && !contentData->next() && contentData->isImage() && !element.isPseudoElement()) {
131         RenderImage* image = new RenderImage(element, std::move(style));
132         if (const StyleImage* styleImage = static_cast<const ImageContentData*>(contentData)->image()) {
133             image->setImageResource(RenderImageResourceStyleImage::create(const_cast<StyleImage&>(*styleImage)));
134             image->setIsGeneratedContent();
135         } else
136             image->setImageResource(RenderImageResource::create());
137         return image;
138     }
139
140     if (element.hasTagName(HTMLNames::rubyTag)) {
141         if (style.get().display() == INLINE)
142             return new RenderRubyAsInline(element, std::move(style));
143         if (style.get().display() == BLOCK)
144             return new RenderRubyAsBlock(element, std::move(style));
145     }
146     // treat <rt> as ruby text ONLY if it still has its default treatment of block
147     if (element.hasTagName(HTMLNames::rtTag) && style.get().display() == BLOCK)
148         return new RenderRubyText(element, std::move(style));
149     switch (style.get().display()) {
150     case NONE:
151         return 0;
152     case INLINE:
153         return new RenderInline(element, std::move(style));
154     case BLOCK:
155     case INLINE_BLOCK:
156     case RUN_IN:
157     case COMPACT:
158         if ((!style.get().hasAutoColumnCount() || !style.get().hasAutoColumnWidth()) && document.regionBasedColumnsEnabled())
159             return new RenderMultiColumnBlock(element, std::move(style));
160         return new RenderBlockFlow(element, std::move(style));
161     case LIST_ITEM:
162         return new RenderListItem(element, std::move(style));
163     case TABLE:
164     case INLINE_TABLE:
165         return new RenderTable(element, std::move(style));
166     case TABLE_ROW_GROUP:
167     case TABLE_HEADER_GROUP:
168     case TABLE_FOOTER_GROUP:
169         return new RenderTableSection(element, std::move(style));
170     case TABLE_ROW:
171         return new RenderTableRow(element, std::move(style));
172     case TABLE_COLUMN_GROUP:
173     case TABLE_COLUMN:
174         return new RenderTableCol(element, std::move(style));
175     case TABLE_CELL:
176         return new RenderTableCell(element, std::move(style));
177     case TABLE_CAPTION:
178         return new RenderTableCaption(element, std::move(style));
179     case BOX:
180     case INLINE_BOX:
181         return new RenderDeprecatedFlexibleBox(element, std::move(style));
182     case FLEX:
183     case INLINE_FLEX:
184         return new RenderFlexibleBox(element, std::move(style));
185     case GRID:
186     case INLINE_GRID:
187         return new RenderGrid(element, std::move(style));
188     }
189     ASSERT_NOT_REACHED();
190     return nullptr;
191 }
192
193 enum StyleCacheState {
194     Cached,
195     Uncached
196 };
197
198 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderElement& renderer, RenderStyle* style)
199 {
200     const RenderElement& rendererForFirstLineStyle = renderer.isBeforeOrAfterContent() ? *renderer.parent() : renderer;
201
202     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
203         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock()) {
204             if (type == Cached)
205                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
206             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == &renderer ? style : nullptr);
207         }
208     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
209         RenderStyle* parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
210         if (parentStyle != rendererForFirstLineStyle.parent()->style()) {
211             if (type == Cached) {
212                 // A first-line style is in effect. Cache a first-line style for ourselves.
213                 rendererForFirstLineStyle.style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
214                 return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
215             }
216             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
217         }
218     }
219     return nullptr;
220 }
221
222 PassRefPtr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
223 {
224     if (!document().styleSheetCollection().usesFirstLineRules())
225         return 0;
226
227     return firstLineStyleForCachedUncachedType(Uncached, *this, style);
228 }
229
230 RenderStyle* RenderElement::cachedFirstLineStyle() const
231 {
232     ASSERT(document().styleSheetCollection().usesFirstLineRules());
233
234     RenderStyle* style = this->style();
235     if (RefPtr<RenderStyle> firstLineStyle = firstLineStyleForCachedUncachedType(Cached, *this, style))
236         return firstLineStyle.get();
237
238     return style;
239 }
240
241 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
242 {
243 #if USE(ACCELERATED_COMPOSITING)
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 && style() && isRenderLayerModelObject()) {
285         if (hasLayer() != toRenderLayerModelObject(this)->requiresLayer())
286             diff = StyleDifferenceLayout;
287     }
288 #else
289     UNUSED_PARAM(contextSensitiveProperties);
290 #endif
291
292     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
293     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
294         diff = StyleDifferenceRepaint;
295
296     return diff;
297 }
298
299 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
300 {
301     for (const RenderObject* renderer = firstChild(); renderer; renderer = renderer->nextSibling()) {
302         if (renderer->isText() && !toRenderText(renderer)->isAllCollapsibleWhitespace())
303             return true;
304         if (renderer->style()->hasOutline() || renderer->style()->hasBorder())
305             return true;
306     }
307     return false;
308 }
309
310 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
311 {
312     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
313 }
314
315 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
316 {
317     // Optimize the common case
318     if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
319         return;
320     
321     // Go through the new layers and addClients first, to avoid removing all clients of an image.
322     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
323         if (currNew->image())
324             currNew->image()->addClient(this);
325     }
326
327     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
328         if (currOld->image())
329             currOld->image()->removeClient(this);
330     }
331 }
332
333 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
334 {
335     if (oldImage == newImage)
336         return;
337     if (oldImage)
338         oldImage->removeClient(this);
339     if (newImage)
340         newImage->addClient(this);
341 }
342
343 #if ENABLE(CSS_SHAPES)
344 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
345 {
346     if (oldShapeValue || newShapeValue)
347         updateImage(oldShapeValue ? oldShapeValue->image() : 0, newShapeValue ? newShapeValue->image() : 0);
348 }
349 #endif
350
351 void RenderElement::initializeStyle()
352 {
353 #if ENABLE(SVG)
354     // FIXME: This logic should be in a less ridiculous place. (This is mirrored from RenderSVGBlock::setStyle().)
355     if (isRenderSVGBlock() && m_style->isDisplayInlineType()) {
356         // SVG text layout code expects us to be a block-level style element.
357         m_style->setDisplay(BLOCK);
358     }
359 #endif
360
361     styleWillChange(StyleDifferenceEqual, *style());
362
363     m_hasInitializedStyle = true;
364
365     updateFillImages(nullptr, m_style->backgroundLayers());
366     updateFillImages(nullptr, m_style->maskLayers());
367
368     updateImage(nullptr, m_style->borderImage().image());
369     updateImage(nullptr, m_style->maskBoxImage().image());
370
371 #if ENABLE(CSS_SHAPES)
372     updateShapeImage(nullptr, m_style->shapeInside());
373     updateShapeImage(nullptr, m_style->shapeOutside());
374 #endif
375
376     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
377     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
378     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
379         view().setMaximalOutlineSize(m_style->outlineSize());
380
381     styleDidChange(StyleDifferenceEqual, nullptr);
382
383 #if !ASSERT_DISABLED
384     // We shouldn't have any text children that would need styleDidChange at this point.
385     for (RenderObject* child = firstChild(); child; child = child->nextSibling())
386         ASSERT(!child->isText());
387 #endif
388
389     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
390     // have their parent set before getting a call to initializeStyle() :|
391 }
392
393 void RenderElement::setStyle(PassRef<RenderStyle> style)
394 {
395     if (&m_style.get() == &style.get()) {
396 #if USE(ACCELERATED_COMPOSITING)
397         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
398         // style sharing is disabled for them. That should ensure that we never hit this code path.
399         ASSERT(!isRenderIFrame() && !isEmbeddedObject() && !isCanvas());
400 #endif
401         style.dropRef();
402         return;
403     }
404
405     StyleDifference diff = StyleDifferenceEqual;
406     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
407     if (m_hasInitializedStyle)
408         diff = m_style->diff(&style.get(), contextSensitiveProperties);
409
410     diff = adjustStyleDifference(diff, contextSensitiveProperties);
411
412     styleWillChange(diff, style.get());
413
414     Ref<RenderStyle> oldStyle(m_style.replace(std::move(style)));
415
416     updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
417     updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
418
419     updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
420     updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
421
422 #if ENABLE(CSS_SHAPES)
423     updateShapeImage(oldStyle.get().shapeInside(), m_style->shapeInside());
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 (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
438         if (child->isText())
439             toRenderText(child)->styleDidChange(diff, &oldStyle.get());
440     }
441
442     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
443     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
444     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
445     // in the future as we move renderer changes out of layout and into style changes.
446     if (doesNotNeedLayout)
447         return;
448
449     // Now that the layer (if any) has been updated, we need to adjust the diff again,
450     // check whether we should layout now, and decide if we need to repaint.
451     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
452     
453     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
454         if (updatedDiff == StyleDifferenceLayout)
455             setNeedsLayoutAndPrefWidthsRecalc();
456         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
457             setNeedsPositionedMovementLayout(&oldStyle.get());
458         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
459             setNeedsPositionedMovementLayout(&oldStyle.get());
460             setNeedsSimplifiedNormalFlowLayout();
461         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
462             setNeedsSimplifiedNormalFlowLayout();
463     }
464
465     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
466         // Do a repaint with the new style now, e.g., for example if we go from
467         // not having an outline to having an outline.
468         repaint();
469     }
470 }
471
472 void RenderElement::setAnimatableStyle(PassRef<RenderStyle> style)
473 {
474     setStyle(animation().updateAnimations(*this, std::move(style)));
475 }
476
477 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
478 {
479     bool needsTable = false;
480
481     if (newChild->isRenderTableCol()) {
482         RenderTableCol* newTableColumn = toRenderTableCol(newChild);
483         bool isColumnInColumnGroup = newTableColumn->isTableColumn() && isRenderTableCol();
484         needsTable = !isTable() && !isColumnInColumnGroup;
485     } else if (newChild->isTableCaption())
486         needsTable = !isTable();
487     else if (newChild->isTableSection())
488         needsTable = !isTable();
489     else if (newChild->isTableRow())
490         needsTable = !isTableSection();
491     else if (newChild->isTableCell())
492         needsTable = !isTableRow();
493
494     if (needsTable) {
495         RenderTable* table;
496         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
497         if (afterChild && afterChild->isAnonymous() && afterChild->isTable() && !afterChild->isBeforeContent())
498             table = toRenderTable(afterChild);
499         else {
500             table = RenderTable::createAnonymousWithParentRenderer(this);
501             addChild(table, beforeChild);
502         }
503         table->addChild(newChild);
504     } else
505         insertChildInternal(newChild, beforeChild, NotifyChildren);
506
507     if (newChild->isText())
508         toRenderText(newChild)->styleDidChange(StyleDifferenceEqual, nullptr);
509
510     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
511     // <g>s to have renderers - at least that's how our implementation works. Consider:
512     // <g display="none"><foreignObject><body style="position: relative">FOO...
513     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
514     // - when the document is painted, both layers are painted. The <body> layer doesn't
515     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
516     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
517     // and stop creating layers at all for these cases - they're not used anyways.
518     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
519         toRenderLayerModelObject(newChild)->layer()->removeOnlyThisLayer();
520
521 #if ENABLE(SVG)
522     SVGRenderSupport::childAdded(this, newChild);
523 #endif
524 }
525
526 void RenderElement::removeChild(RenderObject& oldChild)
527 {
528     removeChildInternal(oldChild, NotifyChildren);
529 }
530
531 void RenderElement::destroyLeftoverChildren()
532 {
533     while (m_firstChild) {
534         if (m_firstChild->isListMarker() || (m_firstChild->style()->styleType() == FIRST_LETTER && !m_firstChild->isText()))
535             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.
536         else if (m_firstChild->isRunIn() && m_firstChild->node()) {
537             m_firstChild->node()->setRenderer(0);
538             m_firstChild->node()->setNeedsStyleRecalc();
539             m_firstChild->destroy();
540         } else {
541             // 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.
542             if (m_firstChild->node())
543                 m_firstChild->node()->setRenderer(0);
544             m_firstChild->destroy();
545         }
546     }
547 }
548
549 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
550 {
551     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
552     ASSERT(!newChild->parent());
553     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
554
555     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
556         beforeChild = beforeChild->parent();
557
558     // This should never happen, but if it does prevent render tree corruption
559     // where child->parent() ends up being owner but child->nextSibling()->parent()
560     // is not owner.
561     if (beforeChild && beforeChild->parent() != this) {
562         ASSERT_NOT_REACHED();
563         return;
564     }
565
566     newChild->setParent(this);
567
568     if (m_firstChild == beforeChild)
569         m_firstChild = newChild;
570
571     if (beforeChild) {
572         RenderObject* previousSibling = beforeChild->previousSibling();
573         if (previousSibling)
574             previousSibling->setNextSibling(newChild);
575         newChild->setPreviousSibling(previousSibling);
576         newChild->setNextSibling(beforeChild);
577         beforeChild->setPreviousSibling(newChild);
578     } else {
579         if (lastChild())
580             lastChild()->setNextSibling(newChild);
581         newChild->setPreviousSibling(lastChild());
582         m_lastChild = newChild;
583     }
584
585     if (!documentBeingDestroyed()) {
586         if (notifyChildren == NotifyChildren)
587             newChild->insertedIntoTree();
588         RenderCounter::rendererSubtreeAttached(newChild);
589     }
590
591     newChild->setNeedsLayoutAndPrefWidthsRecalc();
592     setPreferredLogicalWidthsDirty(true);
593     if (!normalChildNeedsLayout())
594         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
595
596     if (AXObjectCache* cache = document().axObjectCache())
597         cache->childrenChanged(this);
598 }
599
600 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
601 {
602     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
603     ASSERT(oldChild.parent() == this);
604
605     if (oldChild.isFloatingOrOutOfFlowPositioned())
606         toRenderBox(oldChild).removeFloatingOrPositionedChildFromBlockLists();
607
608     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
609     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
610     // disappears gets repainted properly.
611     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
612         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
613         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
614         if (oldChild.isBody())
615             view().repaintRootContents();
616         else
617             oldChild.repaint();
618     }
619
620     // If we have a line box wrapper, delete it.
621     if (oldChild.isBox())
622         toRenderBox(oldChild).deleteLineBoxWrapper();
623     else if (oldChild.isLineBreak())
624         toRenderLineBreak(oldChild).deleteInlineBoxWrapper();
625
626     // If oldChild is the start or end of the selection, then clear the selection to
627     // avoid problems of invalid pointers.
628     // FIXME: The FrameSelection should be responsible for this when it
629     // is notified of DOM mutations.
630     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
631         view().clearSelection();
632
633     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
634         oldChild.willBeRemovedFromTree();
635
636     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
637     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
638     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
639
640     if (oldChild.previousSibling())
641         oldChild.previousSibling()->setNextSibling(oldChild.nextSibling());
642     if (oldChild.nextSibling())
643         oldChild.nextSibling()->setPreviousSibling(oldChild.previousSibling());
644
645     if (m_firstChild == &oldChild)
646         m_firstChild = oldChild.nextSibling();
647     if (m_lastChild == &oldChild)
648         m_lastChild = oldChild.previousSibling();
649
650     oldChild.setPreviousSibling(nullptr);
651     oldChild.setNextSibling(nullptr);
652     oldChild.setParent(nullptr);
653
654     // rendererRemovedFromTree walks the whole subtree. We can improve performance
655     // by skipping this step when destroying the entire tree.
656     if (!documentBeingDestroyed())
657         RenderCounter::rendererRemovedFromTree(oldChild);
658
659     if (AXObjectCache* cache = document().existingAXObjectCache())
660         cache->childrenChanged(this);
661 }
662
663 static void addLayers(RenderElement* obj, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
664 {
665     if (obj->hasLayer()) {
666         if (!beforeChild && newObject) {
667             // We need to figure out the layer that follows newObject. We only do
668             // this the first time we find a child layer, and then we update the
669             // pointer values for newObject and beforeChild used by everyone else.
670             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
671             newObject = nullptr;
672         }
673         parentLayer->addChild(toRenderLayerModelObject(obj)->layer(), beforeChild);
674         return;
675     }
676
677     for (RenderObject* current = obj->firstChild(); current; current = current->nextSibling()) {
678         if (current->isRenderElement())
679             addLayers(toRenderElement(current), parentLayer, newObject, beforeChild);
680     }
681 }
682
683 void RenderElement::addLayers(RenderLayer* parentLayer)
684 {
685     if (!parentLayer)
686         return;
687
688     RenderElement* renderer = this;
689     RenderLayer* beforeChild = nullptr;
690     WebCore::addLayers(this, parentLayer, renderer, beforeChild);
691 }
692
693 void RenderElement::removeLayers(RenderLayer* parentLayer)
694 {
695     if (!parentLayer)
696         return;
697
698     if (hasLayer()) {
699         parentLayer->removeChild(toRenderLayerModelObject(this)->layer());
700         return;
701     }
702
703     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
704         if (child->isRenderElement())
705             toRenderElement(child)->removeLayers(parentLayer);
706     }
707 }
708
709 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
710 {
711     if (!newParent)
712         return;
713
714     if (hasLayer()) {
715         RenderLayer* layer = toRenderLayerModelObject(this)->layer();
716         ASSERT(oldParent == layer->parent());
717         if (oldParent)
718             oldParent->removeChild(layer);
719         newParent->addChild(layer);
720         return;
721     }
722
723     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
724         if (child->isRenderElement())
725             toRenderElement(child)->moveLayers(oldParent, newParent);
726     }
727 }
728
729 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
730 {
731     // Error check the parent layer passed in. If it's null, we can't find anything.
732     if (!parentLayer)
733         return 0;
734
735     // Step 1: If our layer is a child of the desired parent, then return our layer.
736     RenderLayer* ourLayer = hasLayer() ? toRenderLayerModelObject(this)->layer() : nullptr;
737     if (ourLayer && ourLayer->parent() == parentLayer)
738         return ourLayer;
739
740     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
741     // into our siblings trying to find the next layer whose parent is the desired parent.
742     if (!ourLayer || ourLayer == parentLayer) {
743         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
744             if (!child->isRenderElement())
745                 continue;
746             RenderLayer* nextLayer = toRenderElement(child)->findNextLayer(parentLayer, nullptr, false);
747             if (nextLayer)
748                 return nextLayer;
749         }
750     }
751
752     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
753     // find anything.
754     if (parentLayer == ourLayer)
755         return nullptr;
756
757     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
758     // follow us to see if we can locate a layer.
759     if (checkParent && parent())
760         return parent()->findNextLayer(parentLayer, this, true);
761
762     return nullptr;
763 }
764
765 bool RenderElement::layerCreationAllowedForSubtree() const
766 {
767 #if ENABLE(SVG)
768     RenderElement* parentRenderer = parent();
769     while (parentRenderer) {
770         if (parentRenderer->isSVGHiddenContainer())
771             return false;
772         parentRenderer = parentRenderer->parent();
773     }
774 #endif
775     
776     return true;
777 }
778
779 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
780 {
781     // FIXME: We could save this call when the change only affected non-inherited properties.
782     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
783         if (child->isText())
784             continue;
785         RenderElement& elementChild = toRenderElement(*child);
786         if (!elementChild.isAnonymous() || elementChild.style()->styleType() != NOPSEUDO)
787             continue;
788
789         if (propagationType == PropagateToBlockChildrenOnly && !elementChild.isRenderBlock())
790             continue;
791
792 #if ENABLE(FULLSCREEN_API)
793         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
794             continue;
795 #endif
796
797         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
798         if (elementChild.isRenderFlowThread())
799             continue;
800
801         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), elementChild.style()->display());
802         if (style()->specifiesColumns()) {
803             if (elementChild.style()->specifiesColumns())
804                 newStyle.get().inheritColumnPropertiesFrom(style());
805             if (elementChild.style()->columnSpan())
806                 newStyle.get().setColumnSpan(ColumnSpanAll);
807         }
808
809         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
810         // they contain block descendants of relative or sticky positioned inlines.
811         if (elementChild.isInFlowPositioned() && toRenderBlock(elementChild).isAnonymousBlockContinuation())
812             newStyle.get().setPosition(elementChild.style()->position());
813
814         elementChild.setStyle(std::move(newStyle));
815     }
816 }
817
818 // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
819 // when scrolling a page with a fixed background image. As an optimization, assuming there are
820 // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
821 // ignore the CSS property "background-attachment: fixed".
822 static bool shouldRepaintFixedBackgroundsOnScroll()
823 {
824 #if ENABLE(FAST_MOBILE_SCROLLING)
825     return false;
826 #else
827     return true;
828 #endif
829 }
830
831 static inline bool rendererHasBackground(const RenderElement* renderer)
832 {
833     return renderer && renderer->hasBackground();
834 }
835
836 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
837 {
838     RenderStyle* oldStyle = hasInitializedStyle() ? style() : nullptr;
839     if (oldStyle) {
840         // If our z-index changes value or our visibility changes,
841         // we need to dirty our stacking context's z-order list.
842         bool visibilityChanged = m_style->visibility() != newStyle.visibility()
843             || m_style->zIndex() != newStyle.zIndex()
844             || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
845 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
846         if (visibilityChanged)
847             document().setAnnotatedRegionsDirty(true);
848 #endif
849         if (visibilityChanged) {
850             if (AXObjectCache* cache = document().existingAXObjectCache())
851                 cache->childrenChanged(parent());
852         }
853
854         // Keep layer hierarchy visibility bits up to date if visibility changes.
855         if (m_style->visibility() != newStyle.visibility()) {
856             if (RenderLayer* layer = enclosingLayer()) {
857                 if (newStyle.visibility() == VISIBLE)
858                     layer->setHasVisibleContent();
859                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style()->visibility() != VISIBLE)) {
860                     layer->dirtyVisibleContentStatus();
861                     if (diff > StyleDifferenceRepaintLayer)
862                         repaint();
863                 }
864             }
865         }
866
867         if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
868             repaint();
869         if (isFloating() && (m_style->floating() != newStyle.floating()))
870             // For changes in float styles, we need to conceivably remove ourselves
871             // from the floating objects list.
872             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
873         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
874             // For changes in positioning styles, we need to conceivably remove ourselves
875             // from the positioned objects list.
876             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
877
878         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
879             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
880             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
881
882         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
883             && parent() && parent()->isRenderBlock();
884
885         // reset style flags
886         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
887             setFloating(false);
888             clearPositionedState();
889         }
890         setHorizontalWritingMode(true);
891         setHasBoxDecorations(false);
892         setHasOverflowClip(false);
893         setHasTransform(false);
894         setHasReflection(false);
895     } else {
896         s_affectsParentBlock = false;
897         s_noLongerAffectsParentBlock = false;
898     }
899
900     bool repaintFixedBackgroundsOnScroll = shouldRepaintFixedBackgroundsOnScroll();
901
902     bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyle.hasFixedBackgroundImage();
903     bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && m_style->hasFixedBackgroundImage();
904
905 #if USE(ACCELERATED_COMPOSITING)
906     bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
907     if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
908         if (view().compositor().supportsFixedRootBackgroundCompositing()) {
909             if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
910                 newStyleSlowScroll = false;
911
912             if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
913                 oldStyleSlowScroll = false;
914         }
915     }
916 #endif
917     if (oldStyleSlowScroll != newStyleSlowScroll) {
918         if (oldStyleSlowScroll)
919             view().frameView().removeSlowRepaintObject(this);
920
921         if (newStyleSlowScroll)
922             view().frameView().addSlowRepaintObject(this);
923     }
924 }
925
926 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
927 {
928     ASSERT(a->cursors() != b->cursors());
929     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
930 }
931
932 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
933 {
934     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
935 }
936
937 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
938 {
939     if (s_affectsParentBlock)
940         handleDynamicFloatPositionChange();
941
942     if (s_noLongerAffectsParentBlock)
943         removeAnonymousWrappersForInlinesIfNecessary();
944 #if ENABLE(SVG)
945     SVGRenderSupport::styleChanged(this);
946 #endif
947
948     if (!m_parent)
949         return;
950     
951     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
952         RenderCounter::rendererStyleChanged(this, oldStyle, &m_style.get());
953
954         // If the object already needs layout, then setNeedsLayout won't do
955         // any work. But if the containing block has changed, then we may need
956         // to mark the new containing blocks for layout. The change that can
957         // directly affect the containing block of this object is a change to
958         // the position style.
959         if (needsLayout() && oldStyle->position() != m_style->position())
960             markContainingBlocksForLayout();
961
962         if (diff == StyleDifferenceLayout)
963             setNeedsLayoutAndPrefWidthsRecalc();
964         else
965             setNeedsSimplifiedNormalFlowLayout();
966     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
967         setNeedsPositionedMovementLayout(oldStyle);
968         setNeedsSimplifiedNormalFlowLayout();
969     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
970         setNeedsPositionedMovementLayout(oldStyle);
971
972     // Don't check for repaint here; we need to wait until the layer has been
973     // updated by subclasses before we know if we have to repaint (in setStyle()).
974
975     if (oldStyle && !areCursorsEqual(oldStyle, style()))
976         frame().eventHandler().scheduleCursorUpdate();
977 }
978
979 void RenderElement::insertedIntoTree()
980 {
981     RenderObject::insertedIntoTree();
982
983     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
984     // and don't have a layer attached to ourselves.
985     RenderLayer* layer = nullptr;
986     if (firstChild() || hasLayer()) {
987         layer = parent()->enclosingLayer();
988         addLayers(layer);
989     }
990
991     // If |this| is visible but this object was not, tell the layer it has some visible content
992     // that needs to be drawn and layer visibility optimization can't be used
993     if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
994         if (!layer)
995             layer = parent()->enclosingLayer();
996         if (layer)
997             layer->setHasVisibleContent();
998     }
999 }
1000
1001 void RenderElement::willBeRemovedFromTree()
1002 {
1003     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1004     RenderLayer* layer = nullptr;
1005     if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
1006         if ((layer = parent()->enclosingLayer()))
1007             layer->dirtyVisibleContentStatus();
1008     }
1009     // Keep our layer hierarchy updated.
1010     if (firstChild() || hasLayer()) {
1011         if (!layer)
1012             layer = parent()->enclosingLayer();
1013         removeLayers(layer);
1014     }
1015
1016     bool repaintFixedBackgroundsOnScroll = shouldRepaintFixedBackgroundsOnScroll();
1017     if (repaintFixedBackgroundsOnScroll && m_style->hasFixedBackgroundImage())
1018         view().frameView().removeSlowRepaintObject(this);
1019
1020     if (isOutOfFlowPositioned() && parent()->childrenInline())
1021         parent()->dirtyLinesFromChangedChild(this);
1022
1023     RenderObject::willBeRemovedFromTree();
1024 }
1025
1026 void RenderElement::willBeDestroyed()
1027 {
1028     animation().cancelAnimations(this);
1029
1030     destroyLeftoverChildren();
1031
1032     RenderObject::willBeDestroyed();
1033 }
1034
1035 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1036 {
1037     ASSERT(!isSetNeedsLayoutForbidden());
1038     if (needsPositionedMovementLayout())
1039         return;
1040     setNeedsPositionedMovementLayoutBit(true);
1041     markContainingBlocksForLayout();
1042     if (hasLayer()) {
1043         if (oldStyle && style()->diffRequiresRepaint(oldStyle))
1044             setLayerNeedsFullRepaint();
1045         else
1046             setLayerNeedsFullRepaintForPositionedMovementLayout();
1047     }
1048 }
1049
1050 void RenderElement::clearChildNeedsLayout()
1051 {
1052     setNormalChildNeedsLayoutBit(false);
1053     setPosChildNeedsLayoutBit(false);
1054     setNeedsSimplifiedNormalFlowLayoutBit(false);
1055     setNormalChildNeedsLayoutBit(false);
1056     setNeedsPositionedMovementLayoutBit(false);
1057 }
1058
1059 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1060 {
1061     ASSERT(!isSetNeedsLayoutForbidden());
1062     if (needsSimplifiedNormalFlowLayout())
1063         return;
1064     setNeedsSimplifiedNormalFlowLayoutBit(true);
1065     markContainingBlocksForLayout();
1066     if (hasLayer())
1067         setLayerNeedsFullRepaint();
1068 }
1069
1070 RenderElement* RenderElement::rendererForRootBackground()
1071 {
1072     ASSERT(isRoot());
1073     if (!hasBackground() && element() && element()->hasTagName(HTMLNames::htmlTag)) {
1074         // Locate the <body> element using the DOM. This is easier than trying
1075         // to crawl around a render tree with potential :before/:after content and
1076         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1077         // render object very easily via the DOM.
1078         if (auto body = document().body()) {
1079             if (body->hasLocalName(HTMLNames::bodyTag)) {
1080                 if (auto renderer = body->renderer())
1081                     return renderer;
1082             }
1083         }
1084     }
1085     return this;
1086 }
1087
1088 RenderElement* RenderElement::hoverAncestor() const
1089 {
1090     // When searching for the hover ancestor and encountering a named flow thread,
1091     // the search will continue with the DOM ancestor of the top-most element
1092     // in the named flow thread.
1093     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1094     RenderElement* hoverAncestor = parent();
1095
1096     // Skip anonymous blocks directly flowed into flow threads as it would
1097     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1098     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1099         hoverAncestor = hoverAncestor->parent();
1100
1101     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1102         hoverAncestor = nullptr;
1103         if (Element* element = this->element()) {
1104             if (auto parent = element->parentNode())
1105                 hoverAncestor = parent->renderer();
1106         }
1107     }
1108
1109     return hoverAncestor;
1110 }
1111
1112 void RenderElement::layout()
1113 {
1114     StackStats::LayoutCheckPoint layoutCheckPoint;
1115     ASSERT(needsLayout());
1116     RenderObject* child = firstChild();
1117     while (child) {
1118         if (child->needsLayout())
1119             toRenderElement(child)->layout();
1120         ASSERT(!child->needsLayout());
1121         child = child->nextSibling();
1122     }
1123     clearNeedsLayout();
1124 }
1125
1126 }