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