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