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