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