f2a51023e00943812bfdaa82cb71e344abb71921
[WebKit-https.git] / Source / WebCore / rendering / RenderElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013 Apple Inc. All rights reserved.
7  * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "RenderElement.h"
27
28 #include "AXObjectCache.h"
29 #include "ContentData.h"
30 #include "ControlStates.h"
31 #include "CursorList.h"
32 #include "ElementChildIterator.h"
33 #include "EventHandler.h"
34 #include "Frame.h"
35 #include "FrameSelection.h"
36 #include "HTMLBodyElement.h"
37 #include "HTMLHtmlElement.h"
38 #include "HTMLNames.h"
39 #include "FlowThreadController.h"
40 #include "RenderBlock.h"
41 #include "RenderCounter.h"
42 #include "RenderDeprecatedFlexibleBox.h"
43 #include "RenderFlexibleBox.h"
44 #include "RenderImage.h"
45 #include "RenderImageResourceStyleImage.h"
46 #include "RenderInline.h"
47 #include "RenderIterator.h"
48 #include "RenderLayer.h"
49 #include "RenderLayerCompositor.h"
50 #include "RenderLineBreak.h"
51 #include "RenderListItem.h"
52 #include "RenderNamedFlowThread.h"
53 #include "RenderRegion.h"
54 #include "RenderTableCaption.h"
55 #include "RenderTableCell.h"
56 #include "RenderTableCol.h"
57 #include "RenderTableRow.h"
58 #include "RenderText.h"
59 #include "RenderTheme.h"
60 #include "RenderView.h"
61 #include "SVGRenderSupport.h"
62 #include "Settings.h"
63 #include "ShadowRoot.h"
64 #include "StyleResolver.h"
65 #include <wtf/MathExtras.h>
66 #include <wtf/StackStats.h>
67
68 #if ENABLE(CSS_GRID_LAYOUT)
69 #include "RenderGrid.h"
70 #endif
71
72 namespace WebCore {
73
74 bool RenderElement::s_affectsParentBlock = false;
75 bool RenderElement::s_noLongerAffectsParentBlock = false;
76     
77 static HashMap<const RenderObject*, ControlStates*>& controlStatesRendererMap()
78 {
79     static NeverDestroyed<HashMap<const RenderObject*, ControlStates*>> map;
80     return map;
81 }
82
83 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
84     : RenderObject(elementOrDocument)
85     , m_baseTypeFlags(baseTypeFlags)
86     , m_ancestorLineBoxDirty(false)
87     , m_hasInitializedStyle(false)
88     , m_renderInlineAlwaysCreatesLineBoxes(false)
89     , m_renderBoxNeedsLazyRepaint(false)
90     , m_hasPausedImageAnimations(false)
91     , m_hasCounterNodeMap(false)
92     , m_isCSSAnimating(false)
93     , m_hasContinuation(false)
94     , m_renderBlockHasMarginBeforeQuirk(false)
95     , m_renderBlockHasMarginAfterQuirk(false)
96     , m_renderBlockHasBorderOrPaddingLogicalWidthChanged(false)
97     , m_renderBlockFlowHasMarkupTruncation(false)
98     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
99     , m_firstChild(nullptr)
100     , m_lastChild(nullptr)
101     , m_style(WTF::move(style))
102 {
103 }
104
105 RenderElement::RenderElement(Element& element, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
106     : RenderElement(static_cast<ContainerNode&>(element), WTF::move(style), baseTypeFlags)
107 {
108 }
109
110 RenderElement::RenderElement(Document& document, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
111     : RenderElement(static_cast<ContainerNode&>(document), WTF::move(style), baseTypeFlags)
112 {
113 }
114
115 RenderElement::~RenderElement()
116 {
117     if (hasInitializedStyle()) {
118         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
119             if (StyleImage* backgroundImage = bgLayer->image())
120                 backgroundImage->removeClient(this);
121         }
122
123         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
124             if (StyleImage* maskImage = maskLayer->image())
125                 maskImage->removeClient(this);
126             else if (maskLayer->maskImage().get())
127                 maskLayer->maskImage()->removeRendererImageClient(this);
128         }
129
130         if (StyleImage* borderImage = m_style->borderImage().image())
131             borderImage->removeClient(this);
132
133         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
134             maskBoxImage->removeClient(this);
135
136 #if ENABLE(CSS_SHAPES)
137         if (auto shapeValue = m_style->shapeOutside()) {
138             if (auto shapeImage = shapeValue->image())
139                 shapeImage->removeClient(this);
140         }
141 #endif
142     }
143     if (m_hasPausedImageAnimations)
144         view().removeRendererWithPausedImageAnimations(*this);
145 }
146
147 RenderPtr<RenderElement> RenderElement::createFor(Element& element, Ref<RenderStyle>&& style)
148 {
149     // Minimal support for content properties replacing an entire element.
150     // Works only if we have exactly one piece of content and it's a URL.
151     // Otherwise acts as if we didn't support this feature.
152     const ContentData* contentData = style.get().contentData();
153     if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
154         auto& styleImage = downcast<ImageContentData>(*contentData).image();
155         auto image = createRenderer<RenderImage>(element, WTF::move(style), const_cast<StyleImage*>(&styleImage));
156         image->setIsGeneratedContent();
157         return WTF::move(image);
158     }
159
160     switch (style.get().display()) {
161     case NONE:
162         return nullptr;
163     case INLINE:
164         return createRenderer<RenderInline>(element, WTF::move(style));
165     case BLOCK:
166     case INLINE_BLOCK:
167     case COMPACT:
168         return createRenderer<RenderBlockFlow>(element, WTF::move(style));
169     case LIST_ITEM:
170         return createRenderer<RenderListItem>(element, WTF::move(style));
171     case TABLE:
172     case INLINE_TABLE:
173         return createRenderer<RenderTable>(element, WTF::move(style));
174     case TABLE_ROW_GROUP:
175     case TABLE_HEADER_GROUP:
176     case TABLE_FOOTER_GROUP:
177         return createRenderer<RenderTableSection>(element, WTF::move(style));
178     case TABLE_ROW:
179         return createRenderer<RenderTableRow>(element, WTF::move(style));
180     case TABLE_COLUMN_GROUP:
181     case TABLE_COLUMN:
182         return createRenderer<RenderTableCol>(element, WTF::move(style));
183     case TABLE_CELL:
184         return createRenderer<RenderTableCell>(element, WTF::move(style));
185     case TABLE_CAPTION:
186         return createRenderer<RenderTableCaption>(element, WTF::move(style));
187     case BOX:
188     case INLINE_BOX:
189         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTF::move(style));
190     case FLEX:
191     case INLINE_FLEX:
192     case WEBKIT_FLEX:
193     case WEBKIT_INLINE_FLEX:
194         return createRenderer<RenderFlexibleBox>(element, WTF::move(style));
195 #if ENABLE(CSS_GRID_LAYOUT)
196     case GRID:
197     case INLINE_GRID:
198         return createRenderer<RenderGrid>(element, WTF::move(style));
199 #endif
200     }
201     ASSERT_NOT_REACHED();
202     return nullptr;
203 }
204
205 enum StyleCacheState {
206     Cached,
207     Uncached
208 };
209
210 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderElement& renderer, RenderStyle* style)
211 {
212     RenderElement& rendererForFirstLineStyle = renderer.isBeforeOrAfterContent() ? *renderer.parent() : const_cast<RenderElement&>(renderer);
213
214     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
215         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock()) {
216             if (type == Cached)
217                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
218             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == &renderer ? style : nullptr);
219         }
220     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
221         RenderStyle& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
222         if (&parentStyle != &rendererForFirstLineStyle.parent()->style()) {
223             if (type == Cached) {
224                 // A first-line style is in effect. Cache a first-line style for ourselves.
225                 rendererForFirstLineStyle.style().setHasPseudoStyle(FIRST_LINE_INHERITED);
226                 return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, &parentStyle);
227             }
228             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
229         }
230     }
231     return nullptr;
232 }
233
234 PassRefPtr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
235 {
236     if (!document().styleSheetCollection().usesFirstLineRules())
237         return nullptr;
238
239     return firstLineStyleForCachedUncachedType(Uncached, *this, style);
240 }
241
242 RenderStyle* RenderElement::cachedFirstLineStyle() const
243 {
244     ASSERT(document().styleSheetCollection().usesFirstLineRules());
245
246     RenderStyle& style = this->style();
247     if (RefPtr<RenderStyle> firstLineStyle = firstLineStyleForCachedUncachedType(Cached, *this, &style))
248         return firstLineStyle.get();
249
250     return &style;
251 }
252
253 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
254 {
255     // If transform changed, and we are not composited, need to do a layout.
256     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
257         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
258         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
259             if (!hasLayer())
260                 diff = std::max(diff, StyleDifferenceLayout);
261             else {
262                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
263                 // then we actually need SimplifiedLayoutAndPositionedMovement.
264                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
265             }
266         
267         } else
268             diff = std::max(diff, StyleDifferenceRecompositeLayer);
269     }
270
271     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
272         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
273             diff = std::max(diff, StyleDifferenceRepaintLayer);
274         else
275             diff = std::max(diff, StyleDifferenceRecompositeLayer);
276     }
277
278     if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
279         if (hasLayer()
280             && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
281             && hasClipPath()
282             && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
283             diff = std::max(diff, StyleDifferenceRecompositeLayer);
284         else
285             diff = std::max(diff, StyleDifferenceRepaint);
286     }
287     
288     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
289         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
290         if (!layer->isComposited() || layer->paintsWithFilters())
291             diff = std::max(diff, StyleDifferenceRepaintLayer);
292         else
293             diff = std::max(diff, StyleDifferenceRecompositeLayer);
294     }
295     
296     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
297     // style changing, since it depends on whether we decide to composite these elements. When the
298     // layer status of one of these elements changes, we need to force a layout.
299     if (diff == StyleDifferenceEqual && isRenderLayerModelObject()) {
300         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
301             diff = StyleDifferenceLayout;
302     }
303
304     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
305     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
306         diff = StyleDifferenceRepaint;
307
308     return diff;
309 }
310
311 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
312 {
313     for (auto& child : childrenOfType<RenderObject>(*this)) {
314         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
315             return true;
316         if (child.style().hasOutline() || child.style().hasBorder())
317             return true;
318     }
319     return false;
320 }
321
322 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
323 {
324     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
325 }
326
327 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
328 {
329     // Optimize the common case
330     if (FillLayer::imagesIdentical(oldLayers, newLayers))
331         return;
332     
333     // Go through the new layers and addClients first, to avoid removing all clients of an image.
334     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
335         if (StyleImage* image = currNew->image())
336             image->addClient(this);
337         else if (currNew->maskImage().get())
338             currNew->maskImage()->addRendererImageClient(this);
339     }
340
341     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
342         if (StyleImage* image = currOld->image())
343             image->removeClient(this);
344         else if (currOld->maskImage().get())
345             currOld->maskImage()->removeRendererImageClient(this);
346     }
347 }
348
349 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
350 {
351     if (oldImage == newImage)
352         return;
353     if (oldImage)
354         oldImage->removeClient(this);
355     if (newImage)
356         newImage->addClient(this);
357 }
358
359 #if ENABLE(CSS_SHAPES)
360 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
361 {
362     if (oldShapeValue || newShapeValue)
363         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
364 }
365 #endif
366
367 void RenderElement::initializeStyle()
368 {
369     styleWillChange(StyleDifferenceEqual, style());
370
371     m_hasInitializedStyle = true;
372
373     updateFillImages(nullptr, m_style->backgroundLayers());
374     updateFillImages(nullptr, m_style->maskLayers());
375
376     updateImage(nullptr, m_style->borderImage().image());
377     updateImage(nullptr, m_style->maskBoxImage().image());
378
379 #if ENABLE(CSS_SHAPES)
380     updateShapeImage(nullptr, m_style->shapeOutside());
381 #endif
382
383     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
384     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
385     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
386         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
387
388     styleDidChange(StyleDifferenceEqual, nullptr);
389
390     // We shouldn't have any text children that would need styleDidChange at this point.
391     ASSERT(!childrenOfType<RenderText>(*this).first());
392
393     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
394     // have their parent set before getting a call to initializeStyle() :|
395 }
396
397 void RenderElement::setStyle(Ref<RenderStyle>&& style)
398 {
399     // FIXME: Should change RenderView so it can use initializeStyle too.
400     // If we do that, we can assert m_hasInitializedStyle unconditionally,
401     // and remove the check of m_hasInitializedStyle below too.
402     ASSERT(m_hasInitializedStyle || isRenderView());
403
404     if (m_style.ptr() == style.ptr()) {
405         // FIXME: Can we change things so we never hit this code path?
406         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
407         // style sharing is disabled for them. That should ensure that we never hit this code path.
408         ASSERT(!isRenderIFrame());
409         ASSERT(!isEmbeddedObject());
410         ASSERT(!isCanvas());
411         return;
412     }
413
414     StyleDifference diff = StyleDifferenceEqual;
415     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
416     if (m_hasInitializedStyle)
417         diff = m_style->diff(style.get(), contextSensitiveProperties);
418
419     diff = adjustStyleDifference(diff, contextSensitiveProperties);
420
421     styleWillChange(diff, style.get());
422
423     Ref<RenderStyle> oldStyle(m_style.replace(WTF::move(style)));
424
425     updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
426     updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
427
428     updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
429     updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
430
431 #if ENABLE(CSS_SHAPES)
432     updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
433 #endif
434
435     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
436     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
437     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
438         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
439
440     bool doesNotNeedLayout = !parent();
441
442     styleDidChange(diff, oldStyle.ptr());
443
444     // Text renderers use their parent style. Notify them about the change.
445     for (auto& child : childrenOfType<RenderText>(*this))
446         child.styleDidChange(diff, oldStyle.ptr());
447
448     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
449     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
450     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
451     // in the future as we move renderer changes out of layout and into style changes.
452     if (doesNotNeedLayout)
453         return;
454
455     // Now that the layer (if any) has been updated, we need to adjust the diff again,
456     // check whether we should layout now, and decide if we need to repaint.
457     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
458     
459     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
460         if (updatedDiff == StyleDifferenceLayout)
461             setNeedsLayoutAndPrefWidthsRecalc();
462         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
463             setNeedsPositionedMovementLayout(oldStyle.ptr());
464         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
465             setNeedsPositionedMovementLayout(oldStyle.ptr());
466             setNeedsSimplifiedNormalFlowLayout();
467         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
468             setNeedsSimplifiedNormalFlowLayout();
469     }
470
471     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
472         // Do a repaint with the new style now, e.g., for example if we go from
473         // not having an outline to having an outline.
474         repaint();
475     }
476 }
477
478 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
479 {
480     bool needsTable = false;
481
482     if (is<RenderTableCol>(*newChild)) {
483         RenderTableCol& newTableColumn = downcast<RenderTableCol>(*newChild);
484         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
485         needsTable = !is<RenderTable>(*this) && !isColumnInColumnGroup;
486     } else if (is<RenderTableCaption>(*newChild))
487         needsTable = !is<RenderTable>(*this);
488     else if (is<RenderTableSection>(*newChild))
489         needsTable = !is<RenderTable>(*this);
490     else if (is<RenderTableRow>(*newChild))
491         needsTable = !is<RenderTableSection>(*this);
492     else if (is<RenderTableCell>(*newChild))
493         needsTable = !is<RenderTableRow>(*this);
494
495     if (needsTable) {
496         RenderTable* table;
497         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
498         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
499             table = downcast<RenderTable>(afterChild);
500         else {
501             table = RenderTable::createAnonymousWithParentRenderer(this);
502             addChild(table, beforeChild);
503         }
504         table->addChild(newChild);
505     } else
506         insertChildInternal(newChild, beforeChild, NotifyChildren);
507
508     if (is<RenderText>(*newChild))
509         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
510
511     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
512     // <g>s to have renderers - at least that's how our implementation works. Consider:
513     // <g display="none"><foreignObject><body style="position: relative">FOO...
514     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
515     // - when the document is painted, both layers are painted. The <body> layer doesn't
516     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
517     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
518     // and stop creating layers at all for these cases - they're not used anyways.
519     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
520         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
521
522     SVGRenderSupport::childAdded(*this, *newChild);
523 }
524
525 void RenderElement::removeChild(RenderObject& oldChild)
526 {
527     removeChildInternal(oldChild, NotifyChildren);
528 }
529
530 void RenderElement::destroyLeftoverChildren()
531 {
532     while (m_firstChild) {
533         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
534             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
535         } else {
536             // 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.
537             if (m_firstChild->node())
538                 m_firstChild->node()->setRenderer(nullptr);
539             m_firstChild->destroy();
540         }
541     }
542 }
543
544 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
545 {
546     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
547     ASSERT(!newChild->parent());
548     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
549
550     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
551         beforeChild = beforeChild->parent();
552
553     // This should never happen, but if it does prevent render tree corruption
554     // where child->parent() ends up being owner but child->nextSibling()->parent()
555     // is not owner.
556     if (beforeChild && beforeChild->parent() != this) {
557         ASSERT_NOT_REACHED();
558         return;
559     }
560
561     newChild->setParent(this);
562
563     if (m_firstChild == beforeChild)
564         m_firstChild = newChild;
565
566     if (beforeChild) {
567         RenderObject* previousSibling = beforeChild->previousSibling();
568         if (previousSibling)
569             previousSibling->setNextSibling(newChild);
570         newChild->setPreviousSibling(previousSibling);
571         newChild->setNextSibling(beforeChild);
572         beforeChild->setPreviousSibling(newChild);
573     } else {
574         if (lastChild())
575             lastChild()->setNextSibling(newChild);
576         newChild->setPreviousSibling(lastChild());
577         m_lastChild = newChild;
578     }
579
580     if (!documentBeingDestroyed()) {
581         if (notifyChildren == NotifyChildren)
582             newChild->insertedIntoTree();
583         if (is<RenderElement>(*newChild))
584             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
585     }
586
587     newChild->setNeedsLayoutAndPrefWidthsRecalc();
588     setPreferredLogicalWidthsDirty(true);
589     if (!normalChildNeedsLayout())
590         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
591
592     if (AXObjectCache* cache = document().axObjectCache())
593         cache->childrenChanged(this, newChild);
594 }
595
596 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
597 {
598     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
599     ASSERT(oldChild.parent() == this);
600
601     if (oldChild.isFloatingOrOutOfFlowPositioned())
602         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
603
604     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
605     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
606     // disappears gets repainted properly.
607     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
608         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
609         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
610         if (oldChild.isBody())
611             view().repaintRootContents();
612         else
613             oldChild.repaint();
614     }
615
616     // If we have a line box wrapper, delete it.
617     if (is<RenderBox>(oldChild))
618         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
619     else if (is<RenderLineBreak>(oldChild))
620         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
621
622     // If oldChild is the start or end of the selection, then clear the selection to
623     // avoid problems of invalid pointers.
624     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
625         frame().selection().setNeedsSelectionUpdate();
626
627     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
628         oldChild.willBeRemovedFromTree();
629
630     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
631     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
632     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
633     
634     RenderObject* nextSibling = oldChild.nextSibling();
635
636     if (oldChild.previousSibling())
637         oldChild.previousSibling()->setNextSibling(nextSibling);
638     if (nextSibling)
639         nextSibling->setPreviousSibling(oldChild.previousSibling());
640
641     if (m_firstChild == &oldChild)
642         m_firstChild = nextSibling;
643     if (m_lastChild == &oldChild)
644         m_lastChild = oldChild.previousSibling();
645
646     oldChild.setPreviousSibling(nullptr);
647     oldChild.setNextSibling(nullptr);
648     oldChild.setParent(nullptr);
649
650     // rendererRemovedFromTree walks the whole subtree. We can improve performance
651     // by skipping this step when destroying the entire tree.
652     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
653         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
654
655     if (AXObjectCache* cache = document().existingAXObjectCache())
656         cache->childrenChanged(this);
657 }
658
659 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
660 {
661     if (renderer.hasLayer()) {
662         if (!beforeChild && newObject) {
663             // We need to figure out the layer that follows newObject. We only do
664             // this the first time we find a child layer, and then we update the
665             // pointer values for newObject and beforeChild used by everyone else.
666             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
667             newObject = nullptr;
668         }
669         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
670         return;
671     }
672
673     for (auto& child : childrenOfType<RenderElement>(renderer))
674         addLayers(child, parentLayer, newObject, beforeChild);
675 }
676
677 void RenderElement::addLayers(RenderLayer* parentLayer)
678 {
679     if (!parentLayer)
680         return;
681
682     RenderElement* renderer = this;
683     RenderLayer* beforeChild = nullptr;
684     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
685 }
686
687 void RenderElement::removeLayers(RenderLayer* parentLayer)
688 {
689     if (!parentLayer)
690         return;
691
692     if (hasLayer()) {
693         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
694         return;
695     }
696
697     for (auto& child : childrenOfType<RenderElement>(*this))
698         child.removeLayers(parentLayer);
699 }
700
701 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
702 {
703     if (!newParent)
704         return;
705
706     if (hasLayer()) {
707         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
708         ASSERT(oldParent == layer->parent());
709         if (oldParent)
710             oldParent->removeChild(layer);
711         newParent->addChild(layer);
712         return;
713     }
714
715     for (auto& child : childrenOfType<RenderElement>(*this))
716         child.moveLayers(oldParent, newParent);
717 }
718
719 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
720 {
721     // Error check the parent layer passed in. If it's null, we can't find anything.
722     if (!parentLayer)
723         return nullptr;
724
725     // Step 1: If our layer is a child of the desired parent, then return our layer.
726     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
727     if (ourLayer && ourLayer->parent() == parentLayer)
728         return ourLayer;
729
730     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
731     // into our siblings trying to find the next layer whose parent is the desired parent.
732     if (!ourLayer || ourLayer == parentLayer) {
733         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
734             if (!is<RenderElement>(*child))
735                 continue;
736             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
737             if (nextLayer)
738                 return nextLayer;
739         }
740     }
741
742     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
743     // find anything.
744     if (parentLayer == ourLayer)
745         return nullptr;
746
747     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
748     // follow us to see if we can locate a layer.
749     if (checkParent && parent())
750         return parent()->findNextLayer(parentLayer, this, true);
751
752     return nullptr;
753 }
754
755 bool RenderElement::layerCreationAllowedForSubtree() const
756 {
757     RenderElement* parentRenderer = parent();
758     while (parentRenderer) {
759         if (parentRenderer->isSVGHiddenContainer())
760             return false;
761         parentRenderer = parentRenderer->parent();
762     }
763     
764     return true;
765 }
766
767 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
768 {
769     // FIXME: We could save this call when the change only affected non-inherited properties.
770     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
771         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
772             continue;
773
774         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
775             continue;
776
777 #if ENABLE(FULLSCREEN_API)
778         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
779             continue;
780 #endif
781
782         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
783         if (is<RenderFlowThread>(elementChild))
784             continue;
785
786         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
787         if (style().specifiesColumns()) {
788             if (elementChild.style().specifiesColumns())
789                 newStyle.get().inheritColumnPropertiesFrom(&style());
790             if (elementChild.style().columnSpan())
791                 newStyle.get().setColumnSpan(ColumnSpanAll);
792         }
793
794         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
795         // they contain block descendants of relative or sticky positioned inlines.
796         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
797             newStyle.get().setPosition(elementChild.style().position());
798
799         elementChild.setStyle(WTF::move(newStyle));
800     }
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             downcast<RenderBox>(*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             downcast<RenderBox>(*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         setHasTransformRelatedProperty(false);
870         setHasReflection(false);
871     } else {
872         s_affectsParentBlock = false;
873         s_noLongerAffectsParentBlock = false;
874     }
875
876     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
877     bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
878     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
879         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
880
881         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
882         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
883         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
884         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
885             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
886                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
887                     newStyleSlowScroll = false;
888
889                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
890                     oldStyleSlowScroll = false;
891             }
892         }
893
894         if (oldStyleSlowScroll != newStyleSlowScroll) {
895             if (oldStyleSlowScroll)
896                 view().frameView().removeSlowRepaintObject(this);
897
898             if (newStyleSlowScroll)
899                 view().frameView().addSlowRepaintObject(this);
900         }
901     }
902
903     if (isRoot() || isBody())
904         view().frameView().updateExtendBackgroundIfNecessary();
905 }
906
907 void RenderElement::handleDynamicFloatPositionChange()
908 {
909     // We have gone from not affecting the inline status of the parent flow to suddenly
910     // having an impact.  See if there is a mismatch between the parent flow's
911     // childrenInline() state and our state.
912     setInline(style().isDisplayInlineType());
913     if (isInline() != parent()->childrenInline()) {
914         if (!isInline())
915             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
916         else {
917             // An anonymous block must be made to wrap this inline.
918             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
919             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
920             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
921             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
922         }
923     }
924 }
925
926 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
927 {
928     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
929     if (!parentBlock.canCollapseAnonymousBlockChild())
930         return;
931
932     // We have changed to floated or out-of-flow positioning so maybe all our parent's
933     // children can be inline now. Bail if there are any block children left on the line,
934     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
935     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
936     // if we find a continuation.
937     RenderObject* current = parent()->firstChild();
938     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
939         current = current->nextSibling();
940
941     if (current)
942         return;
943
944     RenderObject* next;
945     for (current = parent()->firstChild(); current; current = next) {
946         next = current->nextSibling();
947         if (current->isAnonymousBlock())
948             parentBlock.collapseAnonymousBoxChild(parentBlock, downcast<RenderBlock>(current));
949     }
950 }
951
952 #if !PLATFORM(IOS)
953 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
954 {
955     ASSERT(a->cursors() != b->cursors());
956     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
957 }
958
959 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
960 {
961     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
962 }
963 #endif
964
965 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
966 {
967     if (s_affectsParentBlock)
968         handleDynamicFloatPositionChange();
969
970     if (s_noLongerAffectsParentBlock)
971         removeAnonymousWrappersForInlinesIfNecessary();
972
973     SVGRenderSupport::styleChanged(*this, oldStyle);
974
975     if (!m_parent)
976         return;
977     
978     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
979         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
980
981         // If the object already needs layout, then setNeedsLayout won't do
982         // any work. But if the containing block has changed, then we may need
983         // to mark the new containing blocks for layout. The change that can
984         // directly affect the containing block of this object is a change to
985         // the position style.
986         if (needsLayout() && oldStyle->position() != m_style->position())
987             markContainingBlocksForLayout();
988
989         if (diff == StyleDifferenceLayout)
990             setNeedsLayoutAndPrefWidthsRecalc();
991         else
992             setNeedsSimplifiedNormalFlowLayout();
993     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
994         setNeedsPositionedMovementLayout(oldStyle);
995         setNeedsSimplifiedNormalFlowLayout();
996     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
997         setNeedsPositionedMovementLayout(oldStyle);
998
999     // Don't check for repaint here; we need to wait until the layer has been
1000     // updated by subclasses before we know if we have to repaint (in setStyle()).
1001
1002 #if !PLATFORM(IOS)
1003     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1004         frame().eventHandler().scheduleCursorUpdate();
1005 #endif
1006 }
1007
1008 void RenderElement::insertedIntoTree()
1009 {
1010     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1011         containerFlowThread->addFlowChild(*this);
1012
1013     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1014     // and don't have a layer attached to ourselves.
1015     RenderLayer* layer = nullptr;
1016     if (firstChild() || hasLayer()) {
1017         layer = parent()->enclosingLayer();
1018         addLayers(layer);
1019     }
1020
1021     // If |this| is visible but this object was not, tell the layer it has some visible content
1022     // that needs to be drawn and layer visibility optimization can't be used
1023     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1024         if (!layer)
1025             layer = parent()->enclosingLayer();
1026         if (layer)
1027             layer->setHasVisibleContent();
1028     }
1029
1030     RenderObject::insertedIntoTree();
1031 }
1032
1033 void RenderElement::willBeRemovedFromTree()
1034 {
1035     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1036     RenderLayer* layer = nullptr;
1037     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1038         if ((layer = parent()->enclosingLayer()))
1039             layer->dirtyVisibleContentStatus();
1040     }
1041     // Keep our layer hierarchy updated.
1042     if (firstChild() || hasLayer()) {
1043         if (!layer)
1044             layer = parent()->enclosingLayer();
1045         removeLayers(layer);
1046     }
1047
1048     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1049         view().frameView().removeSlowRepaintObject(this);
1050
1051     if (isOutOfFlowPositioned() && parent()->childrenInline())
1052         parent()->dirtyLinesFromChangedChild(*this);
1053
1054     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1055         containerFlowThread->removeFlowChild(*this);
1056
1057     RenderObject::willBeRemovedFromTree();
1058 }
1059
1060 void RenderElement::willBeDestroyed()
1061 {
1062     animation().cancelAnimations(*this);
1063
1064     destroyLeftoverChildren();
1065
1066     if (hasCounterNodeMap())
1067         RenderCounter::destroyCounterNodes(*this);
1068
1069     RenderObject::willBeDestroyed();
1070
1071 #if !ASSERT_DISABLED
1072     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1073         // After remove, the object and the associated information should not be in any flow thread.
1074         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1075             ASSERT(!flowThread->hasChild(*this));
1076             ASSERT(!flowThread->hasChildInfo(this));
1077         }
1078     }
1079 #endif
1080 }
1081
1082 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1083 {
1084     ASSERT(!isSetNeedsLayoutForbidden());
1085     if (needsPositionedMovementLayout())
1086         return;
1087     setNeedsPositionedMovementLayoutBit(true);
1088     markContainingBlocksForLayout();
1089     if (hasLayer()) {
1090         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1091             setLayerNeedsFullRepaint();
1092         else
1093             setLayerNeedsFullRepaintForPositionedMovementLayout();
1094     }
1095 }
1096
1097 void RenderElement::clearChildNeedsLayout()
1098 {
1099     setNormalChildNeedsLayoutBit(false);
1100     setPosChildNeedsLayoutBit(false);
1101     setNeedsSimplifiedNormalFlowLayoutBit(false);
1102     setNormalChildNeedsLayoutBit(false);
1103     setNeedsPositionedMovementLayoutBit(false);
1104 }
1105
1106 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1107 {
1108     ASSERT(!isSetNeedsLayoutForbidden());
1109     if (needsSimplifiedNormalFlowLayout())
1110         return;
1111     setNeedsSimplifiedNormalFlowLayoutBit(true);
1112     markContainingBlocksForLayout();
1113     if (hasLayer())
1114         setLayerNeedsFullRepaint();
1115 }
1116
1117 RenderElement& RenderElement::rendererForRootBackground()
1118 {
1119     ASSERT(isRoot());
1120     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1121         // Locate the <body> element using the DOM. This is easier than trying
1122         // to crawl around a render tree with potential :before/:after content and
1123         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1124         // render object very easily via the DOM.
1125         if (auto* body = document().body()) {
1126             if (auto* renderer = body->renderer())
1127                 return *renderer;
1128         }
1129     }
1130     return *this;
1131 }
1132
1133 RenderElement* RenderElement::hoverAncestor() const
1134 {
1135     // When searching for the hover ancestor and encountering a named flow thread,
1136     // the search will continue with the DOM ancestor of the top-most element
1137     // in the named flow thread.
1138     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1139     RenderElement* hoverAncestor = parent();
1140
1141     // Skip anonymous blocks directly flowed into flow threads as it would
1142     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1143     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1144         hoverAncestor = hoverAncestor->parent();
1145
1146     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1147         hoverAncestor = nullptr;
1148         if (Element* element = this->element()) {
1149             if (auto parent = element->parentNode())
1150                 hoverAncestor = parent->renderer();
1151         }
1152     }
1153
1154     return hoverAncestor;
1155 }
1156
1157 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1158 {
1159     paintInfo.phase = phase;
1160     element.paint(paintInfo, childPoint);
1161 }
1162
1163 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1164 {
1165     // Paint all phases atomically, as though the element established its own stacking context.
1166     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1167     // This is also used by other elements (e.g. flex items and grid items).
1168     if (paintInfo.phase == PaintPhaseSelection) {
1169         paint(paintInfo, childPoint);
1170     } else if (paintInfo.phase == PaintPhaseForeground) {
1171         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1172         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1173         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1174         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1175         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1176
1177         // Reset |paintInfo| to the original phase.
1178         paintInfo.phase = PaintPhaseForeground;
1179     }
1180 }
1181
1182 void RenderElement::layout()
1183 {
1184     StackStats::LayoutCheckPoint layoutCheckPoint;
1185     ASSERT(needsLayout());
1186     RenderObject* child = firstChild();
1187     while (child) {
1188         if (child->needsLayout())
1189             downcast<RenderElement>(*child).layout();
1190         ASSERT(!child->needsLayout());
1191         child = child->nextSibling();
1192     }
1193     clearNeedsLayout();
1194 }
1195
1196 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1197 {
1198     // Nobody will use multiple layers without wanting fancy positioning.
1199     if (layer->next())
1200         return true;
1201
1202     // Make sure we have a valid image.
1203     StyleImage* image = layer->image();
1204     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1205         return false;
1206
1207     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1208         return true;
1209
1210     EFillSizeType sizeType = layer->sizeType();
1211
1212     if (sizeType == Contain || sizeType == Cover)
1213         return true;
1214
1215     if (sizeType == SizeLength) {
1216         LengthSize size = layer->sizeLength();
1217         if (size.width().isPercent() || size.height().isPercent())
1218             return true;
1219         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1220         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1221             return true;
1222     } else if (image->usesImageContainerSize())
1223         return true;
1224
1225     return false;
1226 }
1227
1228 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1229 {
1230     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1231         return true;
1232
1233     // If we don't have a background/border/mask, then nothing to do.
1234     if (!renderer.hasBoxDecorations())
1235         return false;
1236
1237     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1238         return true;
1239
1240     // Our fill layers are ok. Let's check border.
1241     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1242         return true;
1243
1244     return false;
1245 }
1246
1247 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1248 {
1249     if (view().printing())
1250         return false; // Don't repaint if we're printing.
1251
1252     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1253     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1254     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1255     LayoutRect newOutlineBox;
1256
1257     bool fullRepaint = selfNeedsLayout();
1258     // Presumably a background or a border exists if border-fit:lines was specified.
1259     if (!fullRepaint && style().borderFit() == BorderFitLines)
1260         fullRepaint = true;
1261     if (!fullRepaint) {
1262         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1263         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1264         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1265         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1266             fullRepaint = true;
1267     }
1268
1269     if (!repaintContainer)
1270         repaintContainer = &view();
1271
1272     if (fullRepaint) {
1273         repaintUsingContainer(repaintContainer, oldBounds);
1274         if (newBounds != oldBounds)
1275             repaintUsingContainer(repaintContainer, newBounds);
1276         return true;
1277     }
1278
1279     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1280         return false;
1281
1282     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1283     if (deltaLeft > 0)
1284         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1285     else if (deltaLeft < 0)
1286         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1287
1288     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1289     if (deltaRight > 0)
1290         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1291     else if (deltaRight < 0)
1292         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1293
1294     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1295     if (deltaTop > 0)
1296         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1297     else if (deltaTop < 0)
1298         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1299
1300     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1301     if (deltaBottom > 0)
1302         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1303     else if (deltaBottom < 0)
1304         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1305
1306     if (newOutlineBox == oldOutlineBox)
1307         return false;
1308
1309     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1310     // two rectangles (but typically only one).
1311     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1312     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1313     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1314     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1315     if (width) {
1316         LayoutUnit shadowLeft;
1317         LayoutUnit shadowRight;
1318         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1319         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1320         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1321         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1322         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1323         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1324         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1325             newOutlineBox.y(),
1326             width + decorationsWidth,
1327             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1328         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1329         if (rightRect.x() < right) {
1330             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1331             repaintUsingContainer(repaintContainer, rightRect);
1332         }
1333     }
1334     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1335     if (height) {
1336         LayoutUnit shadowTop;
1337         LayoutUnit shadowBottom;
1338         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1339         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1340         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1341         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1342         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1343             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1344         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1345         LayoutRect bottomRect(newOutlineBox.x(),
1346             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1347             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1348             height + decorationsHeight);
1349         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1350         if (bottomRect.y() < bottom) {
1351             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1352             repaintUsingContainer(repaintContainer, bottomRect);
1353         }
1354     }
1355     return false;
1356 }
1357
1358 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1359 {
1360     ASSERT(style().hasBorder());
1361
1362     StyleImage* borderImage = style().borderImage().image();
1363     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1364 }
1365
1366 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1367 {
1368     auto& frameView = view().frameView();
1369     if (frameView.isOffscreen())
1370         return false;
1371
1372     if (!hasOverflowClip()) {
1373         // FIXME: Computing the overflow rect is expensive if any descendant has
1374         // its own self-painting layer. As a result, we prefer to abort early in
1375         // this case and assume it may cause us to repaint inside the viewport.
1376         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1377             return true;
1378     }
1379
1380     // Compute viewport rect if it was not provided.
1381     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1382     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1383 }
1384
1385 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1386 {
1387     const Document& document = renderer.document();
1388     if (document.inPageCache())
1389         return false;
1390 #if PLATFORM(IOS)
1391     if (document.frame()->timersPaused())
1392         return false;
1393 #endif
1394     if (document.activeDOMObjectsAreSuspended())
1395         return false;
1396     if (renderer.style().visibility() != VISIBLE)
1397         return false;
1398     if (renderer.view().frameView().isOffscreen())
1399         return false;
1400
1401     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1402     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1403     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1404     // can no longer check if it is a background image.
1405     bool backgroundIsPaintedByRoot = renderer.isRoot();
1406     if (renderer.isBody()) {
1407         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1408         ASSERT(rootRenderer.isRoot());
1409         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1410         // FIXME: Should share body background propagation code.
1411         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1412
1413     }
1414     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect(&renderer.view()) : renderer.absoluteClippedOverflowRect();
1415     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1416         return false;
1417
1418     return true;
1419 }
1420
1421 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1422 {
1423     if (document().inPageCache())
1424         return;
1425     auto& frameView = view().frameView();
1426     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1427     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1428         // FIXME: It would be better to pass the image along with the renderer
1429         // so that we can be smarter about detecting if the image is inside the
1430         // viewport in repaintForPausedImageAnimationsIfNeeded().
1431         view().addRendererWithPausedImageAnimations(*this);
1432         return;
1433     }
1434     imageChanged(&image);
1435 }
1436
1437 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1438 {
1439     ASSERT(m_hasPausedImageAnimations);
1440     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1441         return false;
1442     repaint();
1443     return true;
1444 }
1445
1446 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1447 {
1448     auto* renderer = this;
1449     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1450         renderer = renderer->parent();
1451     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1452 }
1453
1454 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1455 {
1456     return controlStatesRendererMap().contains(o);
1457 }
1458
1459 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1460 {
1461     return controlStatesRendererMap().get(o);
1462 }
1463
1464 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1465 {
1466     ControlStates* states = controlStatesRendererMap().get(o);
1467     if (states) {
1468         controlStatesRendererMap().remove(o);
1469         delete states;
1470     }
1471 }
1472
1473 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1474 {
1475     controlStatesRendererMap().add(o, states);
1476 }
1477
1478 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1479 {
1480     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1481         return nullptr;
1482
1483     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1484     if (cachedStyle)
1485         return cachedStyle;
1486
1487     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1488     if (result)
1489         return style().addCachedPseudoStyle(result.release());
1490     return nullptr;
1491 }
1492
1493 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1494 {
1495     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1496         return nullptr;
1497
1498     if (!parentStyle) {
1499         ASSERT(!ownStyle);
1500         parentStyle = &style();
1501     }
1502
1503     if (isAnonymous())
1504         return nullptr;
1505
1506     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1507         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element(), parentStyle, DisallowStyleSharing);
1508         result->setStyleType(FIRST_LINE_INHERITED);
1509         return result.release();
1510     }
1511
1512     return document().ensureStyleResolver().pseudoStyleForElement(element(), pseudoStyleRequest, parentStyle);
1513 }
1514
1515 RenderBlock* RenderElement::containingBlockForFixedPosition() const
1516 {
1517     const RenderElement* object = this;
1518     while (object && !object->canContainFixedPositionObjects())
1519         object = object->parent();
1520
1521     ASSERT(!object || !object->isAnonymousBlock());
1522     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1523 }
1524
1525 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
1526 {
1527     const RenderElement* object = this;
1528     while (object && !object->canContainAbsolutelyPositionedObjects())
1529         object = object->parent();
1530
1531     // For a relatively positioned inline, return its nearest non-anonymous containing block,
1532     // not the inline itself, to avoid having a positioned objects list in all RenderInlines
1533     // and use RenderBlock* as RenderElement::containingBlock's return type.
1534     // Use RenderBlock::container() to obtain the inline.
1535     if (object && !is<RenderBlock>(*object))
1536         object = object->containingBlock();
1537
1538     while (object && object->isAnonymousBlock())
1539         object = object->containingBlock();
1540
1541     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1542 }
1543
1544 static inline bool isNonRenderBlockInline(const RenderElement& object)
1545 {
1546     return (object.isInline() && !object.isReplaced()) || !object.isRenderBlock();
1547 }
1548
1549 RenderBlock* RenderElement::containingBlockForObjectInFlow() const
1550 {
1551     const RenderElement* object = this;
1552     while (object && isNonRenderBlockInline(*object))
1553         object = object->parent();
1554     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1555 }
1556
1557 Color RenderElement::selectionColor(int colorProperty) const
1558 {
1559     // If the element is unselectable, or we are only painting the selection,
1560     // don't override the foreground color with the selection foreground color.
1561     if (style().userSelect() == SELECT_NONE
1562         || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1563         return Color();
1564
1565     if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1566         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1567         if (!color.isValid())
1568             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1569         return color;
1570     }
1571
1572     if (frame().selection().isFocusedAndActive())
1573         return theme().activeSelectionForegroundColor();
1574     return theme().inactiveSelectionForegroundColor();
1575 }
1576
1577 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1578 {
1579     if (isAnonymous())
1580         return nullptr;
1581
1582     if (ShadowRoot* root = element()->containingShadowRoot()) {
1583         if (root->type() == ShadowRoot::UserAgentShadowRoot) {
1584             if (Element* shadowHost = element()->shadowHost())
1585                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1586         }
1587     }
1588
1589     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1590 }
1591
1592 Color RenderElement::selectionForegroundColor() const
1593 {
1594     return selectionColor(CSSPropertyWebkitTextFillColor);
1595 }
1596
1597 Color RenderElement::selectionEmphasisMarkColor() const
1598 {
1599     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1600 }
1601
1602 Color RenderElement::selectionBackgroundColor() const
1603 {
1604     if (style().userSelect() == SELECT_NONE)
1605         return Color();
1606
1607     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1608         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1609
1610     RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1611     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1612         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1613
1614     if (frame().selection().isFocusedAndActive())
1615         return theme().activeSelectionBackgroundColor();
1616     return theme().inactiveSelectionBackgroundColor();
1617 }
1618
1619 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1620 {
1621     if (!isInline() || isReplaced()) {
1622         point = localToAbsolute(FloatPoint(), UseTransforms);
1623         return true;
1624     }
1625
1626     // find the next text/image child, to get a position
1627     const RenderObject* o = this;
1628     while (o) {
1629         const RenderObject* p = o;
1630         if (RenderObject* child = o->firstChildSlow())
1631             o = child;
1632         else if (o->nextSibling())
1633             o = o->nextSibling();
1634         else {
1635             RenderObject* next = 0;
1636             while (!next && o->parent()) {
1637                 o = o->parent();
1638                 next = o->nextSibling();
1639             }
1640             o = next;
1641
1642             if (!o)
1643                 break;
1644         }
1645         ASSERT(o);
1646
1647         if (!o->isInline() || o->isReplaced()) {
1648             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1649             return true;
1650         }
1651
1652         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1653             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1654         } else if (is<RenderText>(*o) || o->isReplaced()) {
1655             point = FloatPoint();
1656             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1657                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1658             else if (is<RenderBox>(*o))
1659                 point.moveBy(downcast<RenderBox>(*o).location());
1660             point = o->container()->localToAbsolute(point, UseTransforms);
1661             return true;
1662         }
1663     }
1664     
1665     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1666     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1667     if (!o && document().view()) {
1668         point = FloatPoint(0, document().view()->contentsHeight());
1669         return true;
1670     }
1671     return false;
1672 }
1673
1674 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1675 {
1676     if (!isInline() || isReplaced()) {
1677         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1678         return true;
1679     }
1680
1681     // find the last text/image child, to get a position
1682     const RenderObject* o = this;
1683     while (o) {
1684         if (RenderObject* child = o->lastChildSlow())
1685             o = child;
1686         else if (o->previousSibling())
1687             o = o->previousSibling();
1688         else {
1689             RenderObject* prev = 0;
1690             while (!prev) {
1691                 o = o->parent();
1692                 if (!o)
1693                     return false;
1694                 prev = o->previousSibling();
1695             }
1696             o = prev;
1697         }
1698         ASSERT(o);
1699         if (is<RenderText>(*o) || o->isReplaced()) {
1700             point = FloatPoint();
1701             if (is<RenderText>(*o)) {
1702                 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1703                 if (!linesBox.maxX() && !linesBox.maxY())
1704                     continue;
1705                 point.moveBy(linesBox.maxXMaxYCorner());
1706             } else
1707                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1708             point = o->container()->localToAbsolute(point, UseTransforms);
1709             return true;
1710         }
1711     }
1712     return true;
1713 }
1714
1715 LayoutRect RenderElement::anchorRect() const
1716 {
1717     FloatPoint leading, trailing;
1718     bool foundLeading = getLeadingCorner(leading);
1719     bool foundTrailing = getTrailingCorner(trailing);
1720     
1721     // If we've found one corner, but not the other,
1722     // then we should just return a point at the corner that we did find.
1723     if (foundLeading != foundTrailing) {
1724         if (foundLeading)
1725             foundTrailing = foundLeading;
1726         else
1727             foundLeading = foundTrailing;
1728     }
1729
1730     FloatPoint upperLeft = leading;
1731     FloatPoint lowerRight = trailing;
1732
1733     // Vertical writing modes might mean the leading point is not in the top left
1734     if (!isInline() || isReplaced()) {
1735         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1736         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1737     } // Otherwise, it's not obvious what to do.
1738
1739     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1740 }
1741
1742 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1743 {
1744     const RenderElement* current = this;
1745     do {
1746         if (current->isRenderBlock())
1747             return current;
1748         if (!current->isRenderInline() || current->isRubyText())
1749             return nullptr;
1750         
1751         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1752         if (styleToUse.textDecoration() & textDecoration)
1753             return current;
1754         current = current->parent();
1755     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1756
1757     return current;
1758 }
1759
1760 }