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