a645d89115c5649e5009d2465ed997f46ced1f1d
[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 < 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 (isRoot() || isBody())
908         view().frameView().updateExtendBackgroundIfNecessary();
909 }
910
911 void RenderElement::handleDynamicFloatPositionChange()
912 {
913     // We have gone from not affecting the inline status of the parent flow to suddenly
914     // having an impact.  See if there is a mismatch between the parent flow's
915     // childrenInline() state and our state.
916     setInline(style().isDisplayInlineType());
917     if (isInline() != parent()->childrenInline()) {
918         if (!isInline())
919             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
920         else {
921             // An anonymous block must be made to wrap this inline.
922             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
923             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
924             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
925             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
926         }
927     }
928 }
929
930 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
931 {
932     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
933     if (!parentBlock.canCollapseAnonymousBlockChild())
934         return;
935
936     // We have changed to floated or out-of-flow positioning so maybe all our parent's
937     // children can be inline now. Bail if there are any block children left on the line,
938     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
939     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
940     // if we find a continuation.
941     RenderObject* current = parent()->firstChild();
942     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
943         current = current->nextSibling();
944
945     if (current)
946         return;
947
948     RenderObject* next;
949     for (current = parent()->firstChild(); current; current = next) {
950         next = current->nextSibling();
951         if (current->isAnonymousBlock())
952             parentBlock.collapseAnonymousBoxChild(parentBlock, downcast<RenderBlock>(current));
953     }
954 }
955
956 #if !PLATFORM(IOS)
957 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
958 {
959     ASSERT(a->cursors() != b->cursors());
960     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
961 }
962
963 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
964 {
965     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
966 }
967 #endif
968
969 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
970 {
971     if (s_affectsParentBlock)
972         handleDynamicFloatPositionChange();
973
974     if (s_noLongerAffectsParentBlock)
975         removeAnonymousWrappersForInlinesIfNecessary();
976
977     SVGRenderSupport::styleChanged(*this, oldStyle);
978
979     if (!m_parent)
980         return;
981     
982     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
983         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
984
985         // If the object already needs layout, then setNeedsLayout won't do
986         // any work. But if the containing block has changed, then we may need
987         // to mark the new containing blocks for layout. The change that can
988         // directly affect the containing block of this object is a change to
989         // the position style.
990         if (needsLayout() && oldStyle->position() != m_style->position())
991             markContainingBlocksForLayout();
992
993         if (diff == StyleDifferenceLayout)
994             setNeedsLayoutAndPrefWidthsRecalc();
995         else
996             setNeedsSimplifiedNormalFlowLayout();
997     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
998         setNeedsPositionedMovementLayout(oldStyle);
999         setNeedsSimplifiedNormalFlowLayout();
1000     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1001         setNeedsPositionedMovementLayout(oldStyle);
1002
1003     // Don't check for repaint here; we need to wait until the layer has been
1004     // updated by subclasses before we know if we have to repaint (in setStyle()).
1005
1006 #if !PLATFORM(IOS)
1007     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1008         frame().eventHandler().scheduleCursorUpdate();
1009 #endif
1010 }
1011
1012 void RenderElement::insertedIntoTree()
1013 {
1014     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1015         containerFlowThread->addFlowChild(*this);
1016
1017     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1018     // and don't have a layer attached to ourselves.
1019     RenderLayer* layer = nullptr;
1020     if (firstChild() || hasLayer()) {
1021         layer = parent()->enclosingLayer();
1022         addLayers(layer);
1023     }
1024
1025     // If |this| is visible but this object was not, tell the layer it has some visible content
1026     // that needs to be drawn and layer visibility optimization can't be used
1027     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1028         if (!layer)
1029             layer = parent()->enclosingLayer();
1030         if (layer)
1031             layer->setHasVisibleContent();
1032     }
1033
1034     RenderObject::insertedIntoTree();
1035 }
1036
1037 void RenderElement::willBeRemovedFromTree()
1038 {
1039     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1040     RenderLayer* layer = nullptr;
1041     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1042         if ((layer = parent()->enclosingLayer()))
1043             layer->dirtyVisibleContentStatus();
1044     }
1045     // Keep our layer hierarchy updated.
1046     if (firstChild() || hasLayer()) {
1047         if (!layer)
1048             layer = parent()->enclosingLayer();
1049         removeLayers(layer);
1050     }
1051
1052     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1053         view().frameView().removeSlowRepaintObject(this);
1054
1055     if (isOutOfFlowPositioned() && parent()->childrenInline())
1056         parent()->dirtyLinesFromChangedChild(*this);
1057
1058     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1059         containerFlowThread->removeFlowChild(*this);
1060
1061     RenderObject::willBeRemovedFromTree();
1062 }
1063
1064 void RenderElement::willBeDestroyed()
1065 {
1066     animation().cancelAnimations(*this);
1067
1068     destroyLeftoverChildren();
1069
1070     if (hasCounterNodeMap())
1071         RenderCounter::destroyCounterNodes(*this);
1072
1073     RenderObject::willBeDestroyed();
1074
1075 #if !ASSERT_DISABLED
1076     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1077         // After remove, the object and the associated information should not be in any flow thread.
1078         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1079             ASSERT(!flowThread->hasChild(*this));
1080             ASSERT(!flowThread->hasChildInfo(this));
1081         }
1082     }
1083 #endif
1084 }
1085
1086 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1087 {
1088     ASSERT(!isSetNeedsLayoutForbidden());
1089     if (needsPositionedMovementLayout())
1090         return;
1091     setNeedsPositionedMovementLayoutBit(true);
1092     markContainingBlocksForLayout();
1093     if (hasLayer()) {
1094         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1095             setLayerNeedsFullRepaint();
1096         else
1097             setLayerNeedsFullRepaintForPositionedMovementLayout();
1098     }
1099 }
1100
1101 void RenderElement::clearChildNeedsLayout()
1102 {
1103     setNormalChildNeedsLayoutBit(false);
1104     setPosChildNeedsLayoutBit(false);
1105     setNeedsSimplifiedNormalFlowLayoutBit(false);
1106     setNormalChildNeedsLayoutBit(false);
1107     setNeedsPositionedMovementLayoutBit(false);
1108 }
1109
1110 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1111 {
1112     ASSERT(!isSetNeedsLayoutForbidden());
1113     if (needsSimplifiedNormalFlowLayout())
1114         return;
1115     setNeedsSimplifiedNormalFlowLayoutBit(true);
1116     markContainingBlocksForLayout();
1117     if (hasLayer())
1118         setLayerNeedsFullRepaint();
1119 }
1120
1121 RenderElement& RenderElement::rendererForRootBackground()
1122 {
1123     ASSERT(isRoot());
1124     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1125         // Locate the <body> element using the DOM. This is easier than trying
1126         // to crawl around a render tree with potential :before/:after content and
1127         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1128         // render object very easily via the DOM.
1129         if (auto* body = document().body()) {
1130             if (auto* renderer = body->renderer())
1131                 return *renderer;
1132         }
1133     }
1134     return *this;
1135 }
1136
1137 RenderElement* RenderElement::hoverAncestor() const
1138 {
1139     // When searching for the hover ancestor and encountering a named flow thread,
1140     // the search will continue with the DOM ancestor of the top-most element
1141     // in the named flow thread.
1142     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1143     RenderElement* hoverAncestor = parent();
1144
1145     // Skip anonymous blocks directly flowed into flow threads as it would
1146     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1147     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1148         hoverAncestor = hoverAncestor->parent();
1149
1150     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1151         hoverAncestor = nullptr;
1152         if (Element* element = this->element()) {
1153             if (auto parent = element->parentNode())
1154                 hoverAncestor = parent->renderer();
1155         }
1156     }
1157
1158     return hoverAncestor;
1159 }
1160
1161 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1162 {
1163     paintInfo.phase = phase;
1164     element.paint(paintInfo, childPoint);
1165 }
1166
1167 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1168 {
1169     // Paint all phases atomically, as though the element established its own stacking context.
1170     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1171     // This is also used by other elements (e.g. flex items and grid items).
1172     if (paintInfo.phase == PaintPhaseSelection) {
1173         paint(paintInfo, childPoint);
1174     } else if (paintInfo.phase == PaintPhaseForeground) {
1175         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1176         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1177         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1178         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1179         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1180
1181         // Reset |paintInfo| to the original phase.
1182         paintInfo.phase = PaintPhaseForeground;
1183     }
1184 }
1185
1186 void RenderElement::layout()
1187 {
1188     StackStats::LayoutCheckPoint layoutCheckPoint;
1189     ASSERT(needsLayout());
1190     RenderObject* child = firstChild();
1191     while (child) {
1192         if (child->needsLayout())
1193             downcast<RenderElement>(*child).layout();
1194         ASSERT(!child->needsLayout());
1195         child = child->nextSibling();
1196     }
1197     clearNeedsLayout();
1198 }
1199
1200 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1201 {
1202     // Nobody will use multiple layers without wanting fancy positioning.
1203     if (layer->next())
1204         return true;
1205
1206     // Make sure we have a valid image.
1207     StyleImage* image = layer->image();
1208     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1209         return false;
1210
1211     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1212         return true;
1213
1214     EFillSizeType sizeType = layer->sizeType();
1215
1216     if (sizeType == Contain || sizeType == Cover)
1217         return true;
1218
1219     if (sizeType == SizeLength) {
1220         LengthSize size = layer->sizeLength();
1221         if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1222             return true;
1223         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1224         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1225             return true;
1226     } else if (image->usesImageContainerSize())
1227         return true;
1228
1229     return false;
1230 }
1231
1232 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1233 {
1234     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1235         return true;
1236
1237     // If we don't have a background/border/mask, then nothing to do.
1238     if (!renderer.hasBoxDecorations())
1239         return false;
1240
1241     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1242         return true;
1243
1244     // Our fill layers are ok. Let's check border.
1245     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1246         return true;
1247
1248     return false;
1249 }
1250
1251 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1252 {
1253     if (view().printing())
1254         return false; // Don't repaint if we're printing.
1255
1256     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1257     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1258     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1259     LayoutRect newOutlineBox;
1260
1261     bool fullRepaint = selfNeedsLayout();
1262     // Presumably a background or a border exists if border-fit:lines was specified.
1263     if (!fullRepaint && style().borderFit() == BorderFitLines)
1264         fullRepaint = true;
1265     if (!fullRepaint) {
1266         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1267         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1268         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1269         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1270             fullRepaint = true;
1271     }
1272
1273     if (!repaintContainer)
1274         repaintContainer = &view();
1275
1276     if (fullRepaint) {
1277         repaintUsingContainer(repaintContainer, oldBounds);
1278         if (newBounds != oldBounds)
1279             repaintUsingContainer(repaintContainer, newBounds);
1280         return true;
1281     }
1282
1283     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1284         return false;
1285
1286     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1287     if (deltaLeft > 0)
1288         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1289     else if (deltaLeft < 0)
1290         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1291
1292     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1293     if (deltaRight > 0)
1294         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1295     else if (deltaRight < 0)
1296         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1297
1298     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1299     if (deltaTop > 0)
1300         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1301     else if (deltaTop < 0)
1302         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1303
1304     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1305     if (deltaBottom > 0)
1306         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1307     else if (deltaBottom < 0)
1308         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1309
1310     if (newOutlineBox == oldOutlineBox)
1311         return false;
1312
1313     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1314     // two rectangles (but typically only one).
1315     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1316     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1317     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1318     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1319     if (width) {
1320         LayoutUnit shadowLeft;
1321         LayoutUnit shadowRight;
1322         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1323         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1324         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1325         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1326         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1327         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1328         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1329             newOutlineBox.y(),
1330             width + decorationsWidth,
1331             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1332         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1333         if (rightRect.x() < right) {
1334             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1335             repaintUsingContainer(repaintContainer, rightRect);
1336         }
1337     }
1338     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1339     if (height) {
1340         LayoutUnit shadowTop;
1341         LayoutUnit shadowBottom;
1342         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1343         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1344         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1345         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1346         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1347             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1348         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1349         LayoutRect bottomRect(newOutlineBox.x(),
1350             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1351             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1352             height + decorationsHeight);
1353         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1354         if (bottomRect.y() < bottom) {
1355             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1356             repaintUsingContainer(repaintContainer, bottomRect);
1357         }
1358     }
1359     return false;
1360 }
1361
1362 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1363 {
1364     ASSERT(style().hasBorder());
1365
1366     StyleImage* borderImage = style().borderImage().image();
1367     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1368 }
1369
1370 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1371 {
1372     auto& frameView = view().frameView();
1373     if (frameView.isOffscreen())
1374         return false;
1375
1376     if (!hasOverflowClip()) {
1377         // FIXME: Computing the overflow rect is expensive if any descendant has
1378         // its own self-painting layer. As a result, we prefer to abort early in
1379         // this case and assume it may cause us to repaint inside the viewport.
1380         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1381             return true;
1382     }
1383
1384     // Compute viewport rect if it was not provided.
1385     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1386     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1387 }
1388
1389 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1390 {
1391     const Document& document = renderer.document();
1392     if (document.inPageCache())
1393         return false;
1394 #if PLATFORM(IOS)
1395     if (document.frame()->timersPaused())
1396         return false;
1397 #endif
1398     if (document.activeDOMObjectsAreSuspended())
1399         return false;
1400     if (renderer.style().visibility() != VISIBLE)
1401         return false;
1402     if (renderer.view().frameView().isOffscreen())
1403         return false;
1404
1405     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1406     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1407     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1408     // can no longer check if it is a background image.
1409     bool backgroundIsPaintedByRoot = renderer.isRoot();
1410     if (renderer.isBody()) {
1411         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1412         ASSERT(rootRenderer.isRoot());
1413         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1414         // FIXME: Should share body background propagation code.
1415         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1416
1417     }
1418     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect(&renderer.view()) : renderer.absoluteClippedOverflowRect();
1419     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1420         return false;
1421
1422     return true;
1423 }
1424
1425 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1426 {
1427     if (document().inPageCache())
1428         return;
1429     auto& frameView = view().frameView();
1430     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1431     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1432         // FIXME: It would be better to pass the image along with the renderer
1433         // so that we can be smarter about detecting if the image is inside the
1434         // viewport in repaintForPausedImageAnimationsIfNeeded().
1435         view().addRendererWithPausedImageAnimations(*this);
1436         return;
1437     }
1438     imageChanged(&image);
1439 }
1440
1441 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1442 {
1443     ASSERT(m_hasPausedImageAnimations);
1444     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1445         return false;
1446     repaint();
1447     return true;
1448 }
1449
1450 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1451 {
1452     auto* renderer = this;
1453     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1454         renderer = renderer->parent();
1455     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1456 }
1457
1458 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1459 {
1460     return controlStatesRendererMap().contains(o);
1461 }
1462
1463 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1464 {
1465     return controlStatesRendererMap().get(o);
1466 }
1467
1468 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1469 {
1470     ControlStates* states = controlStatesRendererMap().get(o);
1471     if (states) {
1472         controlStatesRendererMap().remove(o);
1473         delete states;
1474     }
1475 }
1476
1477 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1478 {
1479     controlStatesRendererMap().add(o, states);
1480 }
1481
1482 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1483 {
1484     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1485         return nullptr;
1486
1487     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1488     if (cachedStyle)
1489         return cachedStyle;
1490
1491     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1492     if (result)
1493         return style().addCachedPseudoStyle(result.release());
1494     return nullptr;
1495 }
1496
1497 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1498 {
1499     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1500         return nullptr;
1501
1502     if (!parentStyle) {
1503         ASSERT(!ownStyle);
1504         parentStyle = &style();
1505     }
1506
1507     if (isAnonymous())
1508         return nullptr;
1509
1510     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1511         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element(), parentStyle, DisallowStyleSharing);
1512         result->setStyleType(FIRST_LINE_INHERITED);
1513         return result.release();
1514     }
1515
1516     return document().ensureStyleResolver().pseudoStyleForElement(element(), pseudoStyleRequest, parentStyle);
1517 }
1518
1519 RenderBlock* RenderElement::containingBlockForFixedPosition() const
1520 {
1521     const RenderElement* object = this;
1522     while (object && !object->canContainFixedPositionObjects())
1523         object = object->parent();
1524
1525     ASSERT(!object || !object->isAnonymousBlock());
1526     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1527 }
1528
1529 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
1530 {
1531     const RenderElement* object = this;
1532     while (object && !object->canContainAbsolutelyPositionedObjects())
1533         object = object->parent();
1534
1535     // For a relatively positioned inline, return its nearest non-anonymous containing block,
1536     // not the inline itself, to avoid having a positioned objects list in all RenderInlines
1537     // and use RenderBlock* as RenderElement::containingBlock's return type.
1538     // Use RenderBlock::container() to obtain the inline.
1539     if (object && !is<RenderBlock>(*object))
1540         object = object->containingBlock();
1541
1542     while (object && object->isAnonymousBlock())
1543         object = object->containingBlock();
1544
1545     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1546 }
1547
1548 static inline bool isNonRenderBlockInline(const RenderElement& object)
1549 {
1550     return (object.isInline() && !object.isReplaced()) || !object.isRenderBlock();
1551 }
1552
1553 RenderBlock* RenderElement::containingBlockForObjectInFlow() const
1554 {
1555     const RenderElement* object = this;
1556     while (object && isNonRenderBlockInline(*object))
1557         object = object->parent();
1558     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1559 }
1560
1561 Color RenderElement::selectionColor(int colorProperty) const
1562 {
1563     // If the element is unselectable, or we are only painting the selection,
1564     // don't override the foreground color with the selection foreground color.
1565     if (style().userSelect() == SELECT_NONE
1566         || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1567         return Color();
1568
1569     if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1570         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1571         if (!color.isValid())
1572             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1573         return color;
1574     }
1575
1576     if (frame().selection().isFocusedAndActive())
1577         return theme().activeSelectionForegroundColor();
1578     return theme().inactiveSelectionForegroundColor();
1579 }
1580
1581 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1582 {
1583     if (isAnonymous())
1584         return nullptr;
1585
1586     if (ShadowRoot* root = element()->containingShadowRoot()) {
1587         if (root->type() == ShadowRoot::UserAgentShadowRoot) {
1588             if (Element* shadowHost = element()->shadowHost())
1589                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1590         }
1591     }
1592
1593     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1594 }
1595
1596 Color RenderElement::selectionForegroundColor() const
1597 {
1598     return selectionColor(CSSPropertyWebkitTextFillColor);
1599 }
1600
1601 Color RenderElement::selectionEmphasisMarkColor() const
1602 {
1603     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1604 }
1605
1606 Color RenderElement::selectionBackgroundColor() const
1607 {
1608     if (style().userSelect() == SELECT_NONE)
1609         return Color();
1610
1611     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1612         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1613
1614     RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1615     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1616         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1617
1618     if (frame().selection().isFocusedAndActive())
1619         return theme().activeSelectionBackgroundColor();
1620     return theme().inactiveSelectionBackgroundColor();
1621 }
1622
1623 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1624 {
1625     if (!isInline() || isReplaced()) {
1626         point = localToAbsolute(FloatPoint(), UseTransforms);
1627         return true;
1628     }
1629
1630     // find the next text/image child, to get a position
1631     const RenderObject* o = this;
1632     while (o) {
1633         const RenderObject* p = o;
1634         if (RenderObject* child = o->firstChildSlow())
1635             o = child;
1636         else if (o->nextSibling())
1637             o = o->nextSibling();
1638         else {
1639             RenderObject* next = 0;
1640             while (!next && o->parent()) {
1641                 o = o->parent();
1642                 next = o->nextSibling();
1643             }
1644             o = next;
1645
1646             if (!o)
1647                 break;
1648         }
1649         ASSERT(o);
1650
1651         if (!o->isInline() || o->isReplaced()) {
1652             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1653             return true;
1654         }
1655
1656         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1657             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1658         } else if (is<RenderText>(*o) || o->isReplaced()) {
1659             point = FloatPoint();
1660             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1661                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1662             else if (is<RenderBox>(*o))
1663                 point.moveBy(downcast<RenderBox>(*o).location());
1664             point = o->container()->localToAbsolute(point, UseTransforms);
1665             return true;
1666         }
1667     }
1668     
1669     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1670     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1671     if (!o && document().view()) {
1672         point = FloatPoint(0, document().view()->contentsHeight());
1673         return true;
1674     }
1675     return false;
1676 }
1677
1678 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1679 {
1680     if (!isInline() || isReplaced()) {
1681         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1682         return true;
1683     }
1684
1685     // find the last text/image child, to get a position
1686     const RenderObject* o = this;
1687     while (o) {
1688         if (RenderObject* child = o->lastChildSlow())
1689             o = child;
1690         else if (o->previousSibling())
1691             o = o->previousSibling();
1692         else {
1693             RenderObject* prev = 0;
1694             while (!prev) {
1695                 o = o->parent();
1696                 if (!o)
1697                     return false;
1698                 prev = o->previousSibling();
1699             }
1700             o = prev;
1701         }
1702         ASSERT(o);
1703         if (is<RenderText>(*o) || o->isReplaced()) {
1704             point = FloatPoint();
1705             if (is<RenderText>(*o)) {
1706                 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1707                 if (!linesBox.maxX() && !linesBox.maxY())
1708                     continue;
1709                 point.moveBy(linesBox.maxXMaxYCorner());
1710             } else
1711                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1712             point = o->container()->localToAbsolute(point, UseTransforms);
1713             return true;
1714         }
1715     }
1716     return true;
1717 }
1718
1719 LayoutRect RenderElement::anchorRect() const
1720 {
1721     FloatPoint leading, trailing;
1722     getLeadingCorner(leading);
1723     getTrailingCorner(trailing);
1724
1725     FloatPoint upperLeft = leading;
1726     FloatPoint lowerRight = trailing;
1727
1728     // Vertical writing modes might mean the leading point is not in the top left
1729     if (!isInline() || isReplaced()) {
1730         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1731         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1732     } // Otherwise, it's not obvious what to do.
1733
1734     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1735 }
1736
1737 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1738 {
1739     const RenderElement* current = this;
1740     do {
1741         if (current->isRenderBlock())
1742             return current;
1743         if (!current->isRenderInline() || current->isRubyText())
1744             return nullptr;
1745         
1746         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1747         if (styleToUse.textDecoration() & textDecoration)
1748             return current;
1749         current = current->parent();
1750     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1751
1752     return current;
1753 }
1754
1755 }