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