CSS Scroll Snap - support snapping to nested elements
[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, 2015 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 < StyleDifferenceLayout && 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(StyleDifferenceNewStyle, 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(StyleDifferenceNewStyle, 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, StyleDifference minimalStyleDifference)
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() && minimalStyleDifference != StyleDifferenceEqual) {
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 = std::max(diff, minimalStyleDifference);
420
421     diff = adjustStyleDifference(diff, contextSensitiveProperties);
422
423     styleWillChange(diff, style.get());
424
425     Ref<RenderStyle> oldStyle(m_style.replace(WTF::move(style)));
426
427     updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
428     updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
429
430     updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
431     updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
432
433 #if ENABLE(CSS_SHAPES)
434     updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
435 #endif
436
437     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
438     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
439     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
440         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
441
442     bool doesNotNeedLayout = !parent();
443
444     styleDidChange(diff, oldStyle.ptr());
445
446     // Text renderers use their parent style. Notify them about the change.
447     for (auto& child : childrenOfType<RenderText>(*this))
448         child.styleDidChange(diff, oldStyle.ptr());
449
450     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
451     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
452     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
453     // in the future as we move renderer changes out of layout and into style changes.
454     if (doesNotNeedLayout)
455         return;
456
457     // Now that the layer (if any) has been updated, we need to adjust the diff again,
458     // check whether we should layout now, and decide if we need to repaint.
459     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
460     
461     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
462         if (updatedDiff == StyleDifferenceLayout)
463             setNeedsLayoutAndPrefWidthsRecalc();
464         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
465             setNeedsPositionedMovementLayout(oldStyle.ptr());
466         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
467             setNeedsPositionedMovementLayout(oldStyle.ptr());
468             setNeedsSimplifiedNormalFlowLayout();
469         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
470             setNeedsSimplifiedNormalFlowLayout();
471     }
472
473     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
474         // Do a repaint with the new style now, e.g., for example if we go from
475         // not having an outline to having an outline.
476         repaint();
477     }
478 }
479
480 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
481 {
482     bool needsTable = false;
483
484     if (is<RenderTableCol>(*newChild)) {
485         RenderTableCol& newTableColumn = downcast<RenderTableCol>(*newChild);
486         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
487         needsTable = !is<RenderTable>(*this) && !isColumnInColumnGroup;
488     } else if (is<RenderTableCaption>(*newChild))
489         needsTable = !is<RenderTable>(*this);
490     else if (is<RenderTableSection>(*newChild))
491         needsTable = !is<RenderTable>(*this);
492     else if (is<RenderTableRow>(*newChild))
493         needsTable = !is<RenderTableSection>(*this);
494     else if (is<RenderTableCell>(*newChild))
495         needsTable = !is<RenderTableRow>(*this);
496
497     if (needsTable) {
498         RenderTable* table;
499         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
500         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
501             table = downcast<RenderTable>(afterChild);
502         else {
503             table = RenderTable::createAnonymousWithParentRenderer(this);
504             addChild(table, beforeChild);
505         }
506         table->addChild(newChild);
507     } else
508         insertChildInternal(newChild, beforeChild, NotifyChildren);
509
510     if (is<RenderText>(*newChild))
511         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
512
513     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
514     // <g>s to have renderers - at least that's how our implementation works. Consider:
515     // <g display="none"><foreignObject><body style="position: relative">FOO...
516     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
517     // - when the document is painted, both layers are painted. The <body> layer doesn't
518     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
519     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
520     // and stop creating layers at all for these cases - they're not used anyways.
521     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
522         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
523
524     SVGRenderSupport::childAdded(*this, *newChild);
525 }
526
527 void RenderElement::removeChild(RenderObject& oldChild)
528 {
529     removeChildInternal(oldChild, NotifyChildren);
530 }
531
532 void RenderElement::destroyLeftoverChildren()
533 {
534     while (m_firstChild) {
535         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
536             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
537         } else {
538             // 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.
539             if (m_firstChild->node())
540                 m_firstChild->node()->setRenderer(nullptr);
541             m_firstChild->destroy();
542         }
543     }
544 }
545
546 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
547 {
548     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
549     ASSERT(!newChild->parent());
550     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
551
552     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
553         beforeChild = beforeChild->parent();
554
555     // This should never happen, but if it does prevent render tree corruption
556     // where child->parent() ends up being owner but child->nextSibling()->parent()
557     // is not owner.
558     if (beforeChild && beforeChild->parent() != this) {
559         ASSERT_NOT_REACHED();
560         return;
561     }
562
563     newChild->setParent(this);
564
565     if (m_firstChild == beforeChild)
566         m_firstChild = newChild;
567
568     if (beforeChild) {
569         RenderObject* previousSibling = beforeChild->previousSibling();
570         if (previousSibling)
571             previousSibling->setNextSibling(newChild);
572         newChild->setPreviousSibling(previousSibling);
573         newChild->setNextSibling(beforeChild);
574         beforeChild->setPreviousSibling(newChild);
575     } else {
576         if (lastChild())
577             lastChild()->setNextSibling(newChild);
578         newChild->setPreviousSibling(lastChild());
579         m_lastChild = newChild;
580     }
581
582     if (!documentBeingDestroyed()) {
583         if (notifyChildren == NotifyChildren)
584             newChild->insertedIntoTree();
585         if (is<RenderElement>(*newChild))
586             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
587     }
588
589     newChild->setNeedsLayoutAndPrefWidthsRecalc();
590     setPreferredLogicalWidthsDirty(true);
591     if (!normalChildNeedsLayout())
592         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
593
594     if (AXObjectCache* cache = document().axObjectCache())
595         cache->childrenChanged(this, newChild);
596     if (is<RenderBlockFlow>(*this))
597         downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
598 }
599
600 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
601 {
602     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
603     ASSERT(oldChild.parent() == this);
604
605     if (oldChild.isFloatingOrOutOfFlowPositioned())
606         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
607
608     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
609     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
610     // disappears gets repainted properly.
611     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
612         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
613         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
614         if (oldChild.isBody())
615             view().repaintRootContents();
616         else
617             oldChild.repaint();
618     }
619
620     // If we have a line box wrapper, delete it.
621     if (is<RenderBox>(oldChild))
622         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
623     else if (is<RenderLineBreak>(oldChild))
624         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
625
626     // If oldChild is the start or end of the selection, then clear the selection to
627     // avoid problems of invalid pointers.
628     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
629         frame().selection().setNeedsSelectionUpdate();
630
631     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
632         oldChild.willBeRemovedFromTree();
633
634     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
635     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
636     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
637     
638     RenderObject* nextSibling = oldChild.nextSibling();
639
640     if (oldChild.previousSibling())
641         oldChild.previousSibling()->setNextSibling(nextSibling);
642     if (nextSibling)
643         nextSibling->setPreviousSibling(oldChild.previousSibling());
644
645     if (m_firstChild == &oldChild)
646         m_firstChild = nextSibling;
647     if (m_lastChild == &oldChild)
648         m_lastChild = oldChild.previousSibling();
649
650     oldChild.setPreviousSibling(nullptr);
651     oldChild.setNextSibling(nullptr);
652     oldChild.setParent(nullptr);
653
654     // rendererRemovedFromTree walks the whole subtree. We can improve performance
655     // by skipping this step when destroying the entire tree.
656     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
657         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
658
659     if (AXObjectCache* cache = document().existingAXObjectCache())
660         cache->childrenChanged(this);
661 }
662
663 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
664 {
665     if (renderer.hasLayer()) {
666         if (!beforeChild && newObject) {
667             // We need to figure out the layer that follows newObject. We only do
668             // this the first time we find a child layer, and then we update the
669             // pointer values for newObject and beforeChild used by everyone else.
670             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
671             newObject = nullptr;
672         }
673         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
674         return;
675     }
676
677     for (auto& child : childrenOfType<RenderElement>(renderer))
678         addLayers(child, parentLayer, newObject, beforeChild);
679 }
680
681 void RenderElement::addLayers(RenderLayer* parentLayer)
682 {
683     if (!parentLayer)
684         return;
685
686     RenderElement* renderer = this;
687     RenderLayer* beforeChild = nullptr;
688     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
689 }
690
691 void RenderElement::removeLayers(RenderLayer* parentLayer)
692 {
693     if (!parentLayer)
694         return;
695
696     if (hasLayer()) {
697         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
698         return;
699     }
700
701     for (auto& child : childrenOfType<RenderElement>(*this))
702         child.removeLayers(parentLayer);
703 }
704
705 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
706 {
707     if (!newParent)
708         return;
709
710     if (hasLayer()) {
711         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
712         ASSERT(oldParent == layer->parent());
713         if (oldParent)
714             oldParent->removeChild(layer);
715         newParent->addChild(layer);
716         return;
717     }
718
719     for (auto& child : childrenOfType<RenderElement>(*this))
720         child.moveLayers(oldParent, newParent);
721 }
722
723 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
724 {
725     // Error check the parent layer passed in. If it's null, we can't find anything.
726     if (!parentLayer)
727         return nullptr;
728
729     // Step 1: If our layer is a child of the desired parent, then return our layer.
730     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
731     if (ourLayer && ourLayer->parent() == parentLayer)
732         return ourLayer;
733
734     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
735     // into our siblings trying to find the next layer whose parent is the desired parent.
736     if (!ourLayer || ourLayer == parentLayer) {
737         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
738             if (!is<RenderElement>(*child))
739                 continue;
740             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
741             if (nextLayer)
742                 return nextLayer;
743         }
744     }
745
746     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
747     // find anything.
748     if (parentLayer == ourLayer)
749         return nullptr;
750
751     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
752     // follow us to see if we can locate a layer.
753     if (checkParent && parent())
754         return parent()->findNextLayer(parentLayer, this, true);
755
756     return nullptr;
757 }
758
759 bool RenderElement::layerCreationAllowedForSubtree() const
760 {
761     RenderElement* parentRenderer = parent();
762     while (parentRenderer) {
763         if (parentRenderer->isSVGHiddenContainer())
764             return false;
765         parentRenderer = parentRenderer->parent();
766     }
767     
768     return true;
769 }
770
771 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
772 {
773     // FIXME: We could save this call when the change only affected non-inherited properties.
774     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
775         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
776             continue;
777
778         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
779             continue;
780
781 #if ENABLE(FULLSCREEN_API)
782         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
783             continue;
784 #endif
785
786         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
787         if (is<RenderFlowThread>(elementChild))
788             continue;
789
790         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
791         if (style().specifiesColumns()) {
792             if (elementChild.style().specifiesColumns())
793                 newStyle.get().inheritColumnPropertiesFrom(&style());
794             if (elementChild.style().columnSpan())
795                 newStyle.get().setColumnSpan(ColumnSpanAll);
796         }
797
798         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
799         // they contain block descendants of relative or sticky positioned inlines.
800         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
801             newStyle.get().setPosition(elementChild.style().position());
802
803         elementChild.setStyle(WTF::move(newStyle));
804     }
805 }
806
807 static inline bool rendererHasBackground(const RenderElement* renderer)
808 {
809     return renderer && renderer->hasBackground();
810 }
811
812 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
813 {
814     RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
815     if (oldStyle) {
816         // If our z-index changes value or our visibility changes,
817         // we need to dirty our stacking context's z-order list.
818         bool visibilityChanged = m_style->visibility() != newStyle.visibility()
819             || m_style->zIndex() != newStyle.zIndex()
820             || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
821 #if ENABLE(DASHBOARD_SUPPORT)
822         if (visibilityChanged)
823             document().setAnnotatedRegionsDirty(true);
824 #endif
825 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
826         if (visibilityChanged)
827             document().dirtyTouchEventRects();
828 #endif
829         if (visibilityChanged) {
830             if (AXObjectCache* cache = document().existingAXObjectCache())
831                 cache->childrenChanged(parent(), this);
832         }
833
834         // Keep layer hierarchy visibility bits up to date if visibility changes.
835         if (m_style->visibility() != newStyle.visibility()) {
836             if (RenderLayer* layer = enclosingLayer()) {
837                 if (newStyle.visibility() == VISIBLE)
838                     layer->setHasVisibleContent();
839                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
840                     layer->dirtyVisibleContentStatus();
841                     if (diff > StyleDifferenceRepaintLayer)
842                         repaint();
843                 }
844             }
845         }
846
847         if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
848             repaint();
849         if (isFloating() && (m_style->floating() != newStyle.floating()))
850             // For changes in float styles, we need to conceivably remove ourselves
851             // from the floating objects list.
852             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
853         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
854             // For changes in positioning styles, we need to conceivably remove ourselves
855             // from the positioned objects list.
856             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
857
858         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
859             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
860             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
861
862         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
863             && parent() && parent()->isRenderBlock();
864
865         // reset style flags
866         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
867             setFloating(false);
868             clearPositionedState();
869         }
870         setHorizontalWritingMode(true);
871         setHasBoxDecorations(false);
872         setHasOverflowClip(false);
873         setHasTransformRelatedProperty(false);
874         setHasReflection(false);
875     } else {
876         s_affectsParentBlock = false;
877         s_noLongerAffectsParentBlock = false;
878     }
879
880     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
881     bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
882     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
883         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
884
885         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
886         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
887         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
888         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
889             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
890                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
891                     newStyleSlowScroll = false;
892
893                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
894                     oldStyleSlowScroll = false;
895             }
896         }
897
898         if (oldStyleSlowScroll != newStyleSlowScroll) {
899             if (oldStyleSlowScroll)
900                 view().frameView().removeSlowRepaintObject(this);
901
902             if (newStyleSlowScroll)
903                 view().frameView().addSlowRepaintObject(this);
904         }
905     }
906
907 #if ENABLE(CSS_SCROLL_SNAP)
908     if (!newStyle.scrollSnapCoordinates().isEmpty() || (oldStyle && !oldStyle->scrollSnapCoordinates().isEmpty())) {
909         ASSERT(is<RenderBox>(this));
910         if (newStyle.scrollSnapCoordinates().isEmpty())
911             view().unregisterBoxWithScrollSnapCoordinates(downcast<RenderBox>(*this));
912         else
913             view().registerBoxWithScrollSnapCoordinates(downcast<RenderBox>(*this));
914     }
915 #endif
916
917     if (isRoot() || isBody())
918         view().frameView().updateExtendBackgroundIfNecessary();
919 }
920
921 void RenderElement::handleDynamicFloatPositionChange()
922 {
923     // We have gone from not affecting the inline status of the parent flow to suddenly
924     // having an impact.  See if there is a mismatch between the parent flow's
925     // childrenInline() state and our state.
926     setInline(style().isDisplayInlineType());
927     if (isInline() != parent()->childrenInline()) {
928         if (!isInline())
929             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
930         else {
931             // An anonymous block must be made to wrap this inline.
932             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
933             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
934             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
935             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
936         }
937     }
938 }
939
940 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
941 {
942     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
943     if (!parentBlock.canCollapseAnonymousBlockChild())
944         return;
945
946     // We have changed to floated or out-of-flow positioning so maybe all our parent's
947     // children can be inline now. Bail if there are any block children left on the line,
948     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
949     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
950     // if we find a continuation.
951     RenderObject* current = parent()->firstChild();
952     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
953         current = current->nextSibling();
954
955     if (current)
956         return;
957
958     RenderObject* next;
959     for (current = parent()->firstChild(); current; current = next) {
960         next = current->nextSibling();
961         if (current->isAnonymousBlock())
962             parentBlock.collapseAnonymousBoxChild(parentBlock, downcast<RenderBlock>(current));
963     }
964 }
965
966 #if !PLATFORM(IOS)
967 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
968 {
969     ASSERT(a->cursors() != b->cursors());
970     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
971 }
972
973 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
974 {
975     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
976 }
977 #endif
978
979 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
980 {
981     if (s_affectsParentBlock)
982         handleDynamicFloatPositionChange();
983
984     if (s_noLongerAffectsParentBlock)
985         removeAnonymousWrappersForInlinesIfNecessary();
986
987     SVGRenderSupport::styleChanged(*this, oldStyle);
988
989     if (!m_parent)
990         return;
991     
992     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
993         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
994
995         // If the object already needs layout, then setNeedsLayout won't do
996         // any work. But if the containing block has changed, then we may need
997         // to mark the new containing blocks for layout. The change that can
998         // directly affect the containing block of this object is a change to
999         // the position style.
1000         if (needsLayout() && oldStyle->position() != m_style->position())
1001             markContainingBlocksForLayout();
1002
1003         if (diff == StyleDifferenceLayout)
1004             setNeedsLayoutAndPrefWidthsRecalc();
1005         else
1006             setNeedsSimplifiedNormalFlowLayout();
1007     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1008         setNeedsPositionedMovementLayout(oldStyle);
1009         setNeedsSimplifiedNormalFlowLayout();
1010     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1011         setNeedsPositionedMovementLayout(oldStyle);
1012
1013     // Don't check for repaint here; we need to wait until the layer has been
1014     // updated by subclasses before we know if we have to repaint (in setStyle()).
1015
1016 #if !PLATFORM(IOS)
1017     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1018         frame().eventHandler().scheduleCursorUpdate();
1019 #endif
1020 }
1021
1022 void RenderElement::insertedIntoTree()
1023 {
1024     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1025         containerFlowThread->addFlowChild(*this);
1026
1027     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1028     // and don't have a layer attached to ourselves.
1029     RenderLayer* layer = nullptr;
1030     if (firstChild() || hasLayer()) {
1031         layer = parent()->enclosingLayer();
1032         addLayers(layer);
1033     }
1034
1035     // If |this| is visible but this object was not, tell the layer it has some visible content
1036     // that needs to be drawn and layer visibility optimization can't be used
1037     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1038         if (!layer)
1039             layer = parent()->enclosingLayer();
1040         if (layer)
1041             layer->setHasVisibleContent();
1042     }
1043
1044     RenderObject::insertedIntoTree();
1045 }
1046
1047 void RenderElement::willBeRemovedFromTree()
1048 {
1049     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1050     RenderLayer* layer = nullptr;
1051     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1052         if ((layer = parent()->enclosingLayer()))
1053             layer->dirtyVisibleContentStatus();
1054     }
1055     // Keep our layer hierarchy updated.
1056     if (firstChild() || hasLayer()) {
1057         if (!layer)
1058             layer = parent()->enclosingLayer();
1059         removeLayers(layer);
1060     }
1061
1062     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1063         view().frameView().removeSlowRepaintObject(this);
1064
1065     if (isOutOfFlowPositioned() && parent()->childrenInline())
1066         parent()->dirtyLinesFromChangedChild(*this);
1067
1068     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1069         containerFlowThread->removeFlowChild(*this);
1070
1071     
1072 #if ENABLE(CSS_SCROLL_SNAP)
1073     if (!m_style->scrollSnapCoordinates().isEmpty()) {
1074         ASSERT(is<RenderBox>(this));
1075         view().unregisterBoxWithScrollSnapCoordinates(downcast<RenderBox>(*this));
1076     }
1077 #endif
1078
1079     RenderObject::willBeRemovedFromTree();
1080 }
1081
1082 void RenderElement::willBeDestroyed()
1083 {
1084     animation().cancelAnimations(*this);
1085
1086     destroyLeftoverChildren();
1087
1088     if (hasCounterNodeMap())
1089         RenderCounter::destroyCounterNodes(*this);
1090
1091     RenderObject::willBeDestroyed();
1092
1093 #if !ASSERT_DISABLED
1094     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1095         // After remove, the object and the associated information should not be in any flow thread.
1096         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1097             ASSERT(!flowThread->hasChild(*this));
1098             ASSERT(!flowThread->hasChildInfo(this));
1099         }
1100     }
1101 #endif
1102 }
1103
1104 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1105 {
1106     ASSERT(!isSetNeedsLayoutForbidden());
1107     if (needsPositionedMovementLayout())
1108         return;
1109     setNeedsPositionedMovementLayoutBit(true);
1110     markContainingBlocksForLayout();
1111     if (hasLayer()) {
1112         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1113             setLayerNeedsFullRepaint();
1114         else
1115             setLayerNeedsFullRepaintForPositionedMovementLayout();
1116     }
1117 }
1118
1119 void RenderElement::clearChildNeedsLayout()
1120 {
1121     setNormalChildNeedsLayoutBit(false);
1122     setPosChildNeedsLayoutBit(false);
1123     setNeedsSimplifiedNormalFlowLayoutBit(false);
1124     setNormalChildNeedsLayoutBit(false);
1125     setNeedsPositionedMovementLayoutBit(false);
1126 }
1127
1128 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1129 {
1130     ASSERT(!isSetNeedsLayoutForbidden());
1131     if (needsSimplifiedNormalFlowLayout())
1132         return;
1133     setNeedsSimplifiedNormalFlowLayoutBit(true);
1134     markContainingBlocksForLayout();
1135     if (hasLayer())
1136         setLayerNeedsFullRepaint();
1137 }
1138
1139 RenderElement& RenderElement::rendererForRootBackground()
1140 {
1141     ASSERT(isRoot());
1142     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1143         // Locate the <body> element using the DOM. This is easier than trying
1144         // to crawl around a render tree with potential :before/:after content and
1145         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1146         // render object very easily via the DOM.
1147         if (auto* body = document().body()) {
1148             if (auto* renderer = body->renderer())
1149                 return *renderer;
1150         }
1151     }
1152     return *this;
1153 }
1154
1155 RenderElement* RenderElement::hoverAncestor() const
1156 {
1157     // When searching for the hover ancestor and encountering a named flow thread,
1158     // the search will continue with the DOM ancestor of the top-most element
1159     // in the named flow thread.
1160     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1161     RenderElement* hoverAncestor = parent();
1162
1163     // Skip anonymous blocks directly flowed into flow threads as it would
1164     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1165     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1166         hoverAncestor = hoverAncestor->parent();
1167
1168     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1169         hoverAncestor = nullptr;
1170         if (Element* element = this->element()) {
1171             if (auto parent = element->parentNode())
1172                 hoverAncestor = parent->renderer();
1173         }
1174     }
1175
1176     return hoverAncestor;
1177 }
1178
1179 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1180 {
1181     paintInfo.phase = phase;
1182     element.paint(paintInfo, childPoint);
1183 }
1184
1185 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1186 {
1187     // Paint all phases atomically, as though the element established its own stacking context.
1188     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1189     // This is also used by other elements (e.g. flex items and grid items).
1190     if (paintInfo.phase == PaintPhaseSelection) {
1191         paint(paintInfo, childPoint);
1192     } else if (paintInfo.phase == PaintPhaseForeground) {
1193         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1194         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1195         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1196         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1197         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1198
1199         // Reset |paintInfo| to the original phase.
1200         paintInfo.phase = PaintPhaseForeground;
1201     }
1202 }
1203
1204 void RenderElement::layout()
1205 {
1206     StackStats::LayoutCheckPoint layoutCheckPoint;
1207     ASSERT(needsLayout());
1208     RenderObject* child = firstChild();
1209     while (child) {
1210         if (child->needsLayout())
1211             downcast<RenderElement>(*child).layout();
1212         ASSERT(!child->needsLayout());
1213         child = child->nextSibling();
1214     }
1215     clearNeedsLayout();
1216 }
1217
1218 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1219 {
1220     // Nobody will use multiple layers without wanting fancy positioning.
1221     if (layer->next())
1222         return true;
1223
1224     // Make sure we have a valid image.
1225     StyleImage* image = layer->image();
1226     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1227         return false;
1228
1229     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1230         return true;
1231
1232     EFillSizeType sizeType = layer->sizeType();
1233
1234     if (sizeType == Contain || sizeType == Cover)
1235         return true;
1236
1237     if (sizeType == SizeLength) {
1238         LengthSize size = layer->sizeLength();
1239         if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1240             return true;
1241         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1242         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1243             return true;
1244     } else if (image->usesImageContainerSize())
1245         return true;
1246
1247     return false;
1248 }
1249
1250 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1251 {
1252     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1253         return true;
1254
1255     // If we don't have a background/border/mask, then nothing to do.
1256     if (!renderer.hasBoxDecorations())
1257         return false;
1258
1259     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1260         return true;
1261
1262     // Our fill layers are ok. Let's check border.
1263     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1264         return true;
1265
1266     return false;
1267 }
1268
1269 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1270 {
1271     if (view().printing())
1272         return false; // Don't repaint if we're printing.
1273
1274     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1275     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1276     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1277     LayoutRect newOutlineBox;
1278
1279     bool fullRepaint = selfNeedsLayout();
1280     // Presumably a background or a border exists if border-fit:lines was specified.
1281     if (!fullRepaint && style().borderFit() == BorderFitLines)
1282         fullRepaint = true;
1283     if (!fullRepaint) {
1284         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1285         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1286         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1287         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1288             fullRepaint = true;
1289     }
1290
1291     if (!repaintContainer)
1292         repaintContainer = &view();
1293
1294     if (fullRepaint) {
1295         repaintUsingContainer(repaintContainer, oldBounds);
1296         if (newBounds != oldBounds)
1297             repaintUsingContainer(repaintContainer, newBounds);
1298         return true;
1299     }
1300
1301     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1302         return false;
1303
1304     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1305     if (deltaLeft > 0)
1306         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1307     else if (deltaLeft < 0)
1308         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1309
1310     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1311     if (deltaRight > 0)
1312         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1313     else if (deltaRight < 0)
1314         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1315
1316     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1317     if (deltaTop > 0)
1318         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1319     else if (deltaTop < 0)
1320         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1321
1322     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1323     if (deltaBottom > 0)
1324         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1325     else if (deltaBottom < 0)
1326         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1327
1328     if (newOutlineBox == oldOutlineBox)
1329         return false;
1330
1331     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1332     // two rectangles (but typically only one).
1333     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1334     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1335     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1336     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1337     if (width) {
1338         LayoutUnit shadowLeft;
1339         LayoutUnit shadowRight;
1340         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1341         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1342         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1343         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1344         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1345         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1346         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1347             newOutlineBox.y(),
1348             width + decorationsWidth,
1349             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1350         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1351         if (rightRect.x() < right) {
1352             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1353             repaintUsingContainer(repaintContainer, rightRect);
1354         }
1355     }
1356     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1357     if (height) {
1358         LayoutUnit shadowTop;
1359         LayoutUnit shadowBottom;
1360         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1361         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1362         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1363         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1364         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1365             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1366         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1367         LayoutRect bottomRect(newOutlineBox.x(),
1368             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1369             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1370             height + decorationsHeight);
1371         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1372         if (bottomRect.y() < bottom) {
1373             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1374             repaintUsingContainer(repaintContainer, bottomRect);
1375         }
1376     }
1377     return false;
1378 }
1379
1380 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1381 {
1382     ASSERT(style().hasBorder());
1383
1384     StyleImage* borderImage = style().borderImage().image();
1385     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1386 }
1387
1388 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1389 {
1390     auto& frameView = view().frameView();
1391     if (frameView.isOffscreen())
1392         return false;
1393
1394     if (!hasOverflowClip()) {
1395         // FIXME: Computing the overflow rect is expensive if any descendant has
1396         // its own self-painting layer. As a result, we prefer to abort early in
1397         // this case and assume it may cause us to repaint inside the viewport.
1398         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1399             return true;
1400     }
1401
1402     // Compute viewport rect if it was not provided.
1403     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1404     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1405 }
1406
1407 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1408 {
1409     const Document& document = renderer.document();
1410     if (document.inPageCache())
1411         return false;
1412 #if PLATFORM(IOS)
1413     if (document.frame()->timersPaused())
1414         return false;
1415 #endif
1416     if (document.activeDOMObjectsAreSuspended())
1417         return false;
1418     if (renderer.style().visibility() != VISIBLE)
1419         return false;
1420     if (renderer.view().frameView().isOffscreen())
1421         return false;
1422
1423     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1424     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1425     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1426     // can no longer check if it is a background image.
1427     bool backgroundIsPaintedByRoot = renderer.isRoot();
1428     if (renderer.isBody()) {
1429         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1430         ASSERT(rootRenderer.isRoot());
1431         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1432         // FIXME: Should share body background propagation code.
1433         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1434
1435     }
1436     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect(&renderer.view()) : renderer.absoluteClippedOverflowRect();
1437     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1438         return false;
1439
1440     return true;
1441 }
1442
1443 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1444 {
1445     if (document().inPageCache())
1446         return;
1447     auto& frameView = view().frameView();
1448     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1449     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1450         // FIXME: It would be better to pass the image along with the renderer
1451         // so that we can be smarter about detecting if the image is inside the
1452         // viewport in repaintForPausedImageAnimationsIfNeeded().
1453         view().addRendererWithPausedImageAnimations(*this);
1454         return;
1455     }
1456     imageChanged(&image);
1457 }
1458
1459 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1460 {
1461     ASSERT(m_hasPausedImageAnimations);
1462     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1463         return false;
1464     repaint();
1465     return true;
1466 }
1467
1468 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1469 {
1470     auto* renderer = this;
1471     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1472         renderer = renderer->parent();
1473     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1474 }
1475
1476 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1477 {
1478     return controlStatesRendererMap().contains(o);
1479 }
1480
1481 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1482 {
1483     return controlStatesRendererMap().get(o);
1484 }
1485
1486 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1487 {
1488     ControlStates* states = controlStatesRendererMap().get(o);
1489     if (states) {
1490         controlStatesRendererMap().remove(o);
1491         delete states;
1492     }
1493 }
1494
1495 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1496 {
1497     controlStatesRendererMap().add(o, states);
1498 }
1499
1500 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1501 {
1502     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1503         return nullptr;
1504
1505     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1506     if (cachedStyle)
1507         return cachedStyle;
1508
1509     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1510     if (result)
1511         return style().addCachedPseudoStyle(result.release());
1512     return nullptr;
1513 }
1514
1515 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1516 {
1517     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1518         return nullptr;
1519
1520     if (!parentStyle) {
1521         ASSERT(!ownStyle);
1522         parentStyle = &style();
1523     }
1524
1525     if (isAnonymous())
1526         return nullptr;
1527
1528     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1529         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element(), parentStyle, DisallowStyleSharing);
1530         result->setStyleType(FIRST_LINE_INHERITED);
1531         return result.release();
1532     }
1533
1534     return document().ensureStyleResolver().pseudoStyleForElement(element(), pseudoStyleRequest, parentStyle);
1535 }
1536
1537 RenderBlock* RenderElement::containingBlockForFixedPosition() const
1538 {
1539     const RenderElement* object = this;
1540     while (object && !object->canContainFixedPositionObjects())
1541         object = object->parent();
1542
1543     ASSERT(!object || !object->isAnonymousBlock());
1544     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1545 }
1546
1547 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
1548 {
1549     const RenderElement* object = this;
1550     while (object && !object->canContainAbsolutelyPositionedObjects())
1551         object = object->parent();
1552
1553     // For a relatively positioned inline, return its nearest non-anonymous containing block,
1554     // not the inline itself, to avoid having a positioned objects list in all RenderInlines
1555     // and use RenderBlock* as RenderElement::containingBlock's return type.
1556     // Use RenderBlock::container() to obtain the inline.
1557     if (object && !is<RenderBlock>(*object))
1558         object = object->containingBlock();
1559
1560     while (object && object->isAnonymousBlock())
1561         object = object->containingBlock();
1562
1563     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1564 }
1565
1566 static inline bool isNonRenderBlockInline(const RenderElement& object)
1567 {
1568     return (object.isInline() && !object.isReplaced()) || !object.isRenderBlock();
1569 }
1570
1571 RenderBlock* RenderElement::containingBlockForObjectInFlow() const
1572 {
1573     const RenderElement* object = this;
1574     while (object && isNonRenderBlockInline(*object))
1575         object = object->parent();
1576     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1577 }
1578
1579 Color RenderElement::selectionColor(int colorProperty) const
1580 {
1581     // If the element is unselectable, or we are only painting the selection,
1582     // don't override the foreground color with the selection foreground color.
1583     if (style().userSelect() == SELECT_NONE
1584         || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1585         return Color();
1586
1587     if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1588         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1589         if (!color.isValid())
1590             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1591         return color;
1592     }
1593
1594     if (frame().selection().isFocusedAndActive())
1595         return theme().activeSelectionForegroundColor();
1596     return theme().inactiveSelectionForegroundColor();
1597 }
1598
1599 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1600 {
1601     if (isAnonymous())
1602         return nullptr;
1603
1604     if (ShadowRoot* root = element()->containingShadowRoot()) {
1605         if (root->type() == ShadowRoot::UserAgentShadowRoot) {
1606             if (Element* shadowHost = element()->shadowHost())
1607                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1608         }
1609     }
1610
1611     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1612 }
1613
1614 Color RenderElement::selectionForegroundColor() const
1615 {
1616     return selectionColor(CSSPropertyWebkitTextFillColor);
1617 }
1618
1619 Color RenderElement::selectionEmphasisMarkColor() const
1620 {
1621     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1622 }
1623
1624 Color RenderElement::selectionBackgroundColor() const
1625 {
1626     if (style().userSelect() == SELECT_NONE)
1627         return Color();
1628
1629     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1630         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1631
1632     RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1633     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1634         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1635
1636     if (frame().selection().isFocusedAndActive())
1637         return theme().activeSelectionBackgroundColor();
1638     return theme().inactiveSelectionBackgroundColor();
1639 }
1640
1641 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1642 {
1643     if (!isInline() || isReplaced()) {
1644         point = localToAbsolute(FloatPoint(), UseTransforms);
1645         return true;
1646     }
1647
1648     // find the next text/image child, to get a position
1649     const RenderObject* o = this;
1650     while (o) {
1651         const RenderObject* p = o;
1652         if (RenderObject* child = o->firstChildSlow())
1653             o = child;
1654         else if (o->nextSibling())
1655             o = o->nextSibling();
1656         else {
1657             RenderObject* next = 0;
1658             while (!next && o->parent()) {
1659                 o = o->parent();
1660                 next = o->nextSibling();
1661             }
1662             o = next;
1663
1664             if (!o)
1665                 break;
1666         }
1667         ASSERT(o);
1668
1669         if (!o->isInline() || o->isReplaced()) {
1670             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1671             return true;
1672         }
1673
1674         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1675             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1676         } else if (is<RenderText>(*o) || o->isReplaced()) {
1677             point = FloatPoint();
1678             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1679                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1680             else if (is<RenderBox>(*o))
1681                 point.moveBy(downcast<RenderBox>(*o).location());
1682             point = o->container()->localToAbsolute(point, UseTransforms);
1683             return true;
1684         }
1685     }
1686     
1687     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1688     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1689     if (!o && document().view()) {
1690         point = FloatPoint(0, document().view()->contentsHeight());
1691         return true;
1692     }
1693     return false;
1694 }
1695
1696 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1697 {
1698     if (!isInline() || isReplaced()) {
1699         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1700         return true;
1701     }
1702
1703     // find the last text/image child, to get a position
1704     const RenderObject* o = this;
1705     while (o) {
1706         if (RenderObject* child = o->lastChildSlow())
1707             o = child;
1708         else if (o->previousSibling())
1709             o = o->previousSibling();
1710         else {
1711             RenderObject* prev = 0;
1712             while (!prev) {
1713                 o = o->parent();
1714                 if (!o)
1715                     return false;
1716                 prev = o->previousSibling();
1717             }
1718             o = prev;
1719         }
1720         ASSERT(o);
1721         if (is<RenderText>(*o) || o->isReplaced()) {
1722             point = FloatPoint();
1723             if (is<RenderText>(*o)) {
1724                 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1725                 if (!linesBox.maxX() && !linesBox.maxY())
1726                     continue;
1727                 point.moveBy(linesBox.maxXMaxYCorner());
1728             } else
1729                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1730             point = o->container()->localToAbsolute(point, UseTransforms);
1731             return true;
1732         }
1733     }
1734     return true;
1735 }
1736
1737 LayoutRect RenderElement::anchorRect() const
1738 {
1739     FloatPoint leading, trailing;
1740     getLeadingCorner(leading);
1741     getTrailingCorner(trailing);
1742
1743     FloatPoint upperLeft = leading;
1744     FloatPoint lowerRight = trailing;
1745
1746     // Vertical writing modes might mean the leading point is not in the top left
1747     if (!isInline() || isReplaced()) {
1748         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1749         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1750     } // Otherwise, it's not obvious what to do.
1751
1752     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1753 }
1754
1755 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1756 {
1757     const RenderElement* current = this;
1758     do {
1759         if (current->isRenderBlock())
1760             return current;
1761         if (!current->isRenderInline() || current->isRubyText())
1762             return nullptr;
1763         
1764         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1765         if (styleToUse.textDecoration() & textDecoration)
1766             return current;
1767         current = current->parent();
1768     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1769
1770     return current;
1771 }
1772
1773 }