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