Source/WebCore:
[WebKit-https.git] / Source / WebCore / rendering / RenderElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013, 2015 Apple Inc. All rights reserved.
7  * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "RenderElement.h"
27
28 #include "AXObjectCache.h"
29 #include "ContentData.h"
30 #include "ControlStates.h"
31 #include "CursorList.h"
32 #include "ElementChildIterator.h"
33 #include "EventHandler.h"
34 #include "FocusController.h"
35 #include "Frame.h"
36 #include "FrameSelection.h"
37 #include "HTMLBodyElement.h"
38 #include "HTMLHtmlElement.h"
39 #include "HTMLNames.h"
40 #include "FlowThreadController.h"
41 #include "PathUtilities.h"
42 #include "RenderBlock.h"
43 #include "RenderCounter.h"
44 #include "RenderDeprecatedFlexibleBox.h"
45 #include "RenderFlexibleBox.h"
46 #include "RenderImage.h"
47 #include "RenderImageResourceStyleImage.h"
48 #include "RenderInline.h"
49 #include "RenderIterator.h"
50 #include "RenderLayer.h"
51 #include "RenderLayerCompositor.h"
52 #include "RenderLineBreak.h"
53 #include "RenderListItem.h"
54 #include "RenderNamedFlowThread.h"
55 #include "RenderRegion.h"
56 #include "RenderTableCaption.h"
57 #include "RenderTableCell.h"
58 #include "RenderTableCol.h"
59 #include "RenderTableRow.h"
60 #include "RenderText.h"
61 #include "RenderTheme.h"
62 #include "RenderView.h"
63 #include "SVGRenderSupport.h"
64 #include "Settings.h"
65 #include "ShadowRoot.h"
66 #include "StyleResolver.h"
67 #include <wtf/MathExtras.h>
68 #include <wtf/StackStats.h>
69
70 #if ENABLE(CSS_GRID_LAYOUT)
71 #include "RenderGrid.h"
72 #endif
73
74 namespace WebCore {
75
76 bool RenderElement::s_affectsParentBlock = false;
77 bool RenderElement::s_noLongerAffectsParentBlock = false;
78     
79 static HashMap<const RenderObject*, ControlStates*>& controlStatesRendererMap()
80 {
81     static NeverDestroyed<HashMap<const RenderObject*, ControlStates*>> map;
82     return map;
83 }
84
85 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
86     : RenderObject(elementOrDocument)
87     , m_baseTypeFlags(baseTypeFlags)
88     , m_ancestorLineBoxDirty(false)
89     , m_hasInitializedStyle(false)
90     , m_renderInlineAlwaysCreatesLineBoxes(false)
91     , m_renderBoxNeedsLazyRepaint(false)
92     , m_hasPausedImageAnimations(false)
93     , m_hasCounterNodeMap(false)
94     , m_isCSSAnimating(false)
95     , m_hasContinuation(false)
96     , m_renderBlockHasMarginBeforeQuirk(false)
97     , m_renderBlockHasMarginAfterQuirk(false)
98     , m_renderBlockShouldForceRelayoutChildren(false)
99     , m_renderBlockFlowHasMarkupTruncation(false)
100     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
101     , m_firstChild(nullptr)
102     , m_lastChild(nullptr)
103     , m_style(WTFMove(style))
104 {
105 }
106
107 RenderElement::RenderElement(Element& element, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
108     : RenderElement(static_cast<ContainerNode&>(element), WTFMove(style), baseTypeFlags)
109 {
110 }
111
112 RenderElement::RenderElement(Document& document, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
113     : RenderElement(static_cast<ContainerNode&>(document), WTFMove(style), baseTypeFlags)
114 {
115 }
116
117 RenderElement::~RenderElement()
118 {
119     if (hasInitializedStyle()) {
120         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
121             if (StyleImage* backgroundImage = bgLayer->image())
122                 backgroundImage->removeClient(this);
123         }
124
125         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
126             if (StyleImage* maskImage = maskLayer->image())
127                 maskImage->removeClient(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     if (isRegisteredForVisibleInViewportCallback())
146         view().unregisterForVisibleInViewportCallback(*this);
147 }
148
149 RenderPtr<RenderElement> RenderElement::createFor(Element& element, Ref<RenderStyle>&& style)
150 {
151     // Minimal support for content properties replacing an entire element.
152     // Works only if we have exactly one piece of content and it's a URL.
153     // Otherwise acts as if we didn't support this feature.
154     const ContentData* contentData = style.get().contentData();
155     if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
156         auto& styleImage = downcast<ImageContentData>(*contentData).image();
157         auto image = createRenderer<RenderImage>(element, WTFMove(style), const_cast<StyleImage*>(&styleImage));
158         image->setIsGeneratedContent();
159         return WTFMove(image);
160     }
161
162     switch (style.get().display()) {
163     case NONE:
164     case CONTENTS:
165         return nullptr;
166     case INLINE:
167         return createRenderer<RenderInline>(element, WTFMove(style));
168     case BLOCK:
169     case INLINE_BLOCK:
170     case COMPACT:
171         return createRenderer<RenderBlockFlow>(element, WTFMove(style));
172     case LIST_ITEM:
173         return createRenderer<RenderListItem>(element, WTFMove(style));
174     case TABLE:
175     case INLINE_TABLE:
176         return createRenderer<RenderTable>(element, WTFMove(style));
177     case TABLE_ROW_GROUP:
178     case TABLE_HEADER_GROUP:
179     case TABLE_FOOTER_GROUP:
180         return createRenderer<RenderTableSection>(element, WTFMove(style));
181     case TABLE_ROW:
182         return createRenderer<RenderTableRow>(element, WTFMove(style));
183     case TABLE_COLUMN_GROUP:
184     case TABLE_COLUMN:
185         return createRenderer<RenderTableCol>(element, WTFMove(style));
186     case TABLE_CELL:
187         return createRenderer<RenderTableCell>(element, WTFMove(style));
188     case TABLE_CAPTION:
189         return createRenderer<RenderTableCaption>(element, WTFMove(style));
190     case BOX:
191     case INLINE_BOX:
192         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTFMove(style));
193     case FLEX:
194     case INLINE_FLEX:
195     case WEBKIT_FLEX:
196     case WEBKIT_INLINE_FLEX:
197         return createRenderer<RenderFlexibleBox>(element, WTFMove(style));
198 #if ENABLE(CSS_GRID_LAYOUT)
199     case GRID:
200     case INLINE_GRID:
201         return createRenderer<RenderGrid>(element, WTFMove(style));
202 #endif
203     }
204     ASSERT_NOT_REACHED();
205     return nullptr;
206 }
207
208 enum StyleCacheState {
209     Cached,
210     Uncached
211 };
212
213 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderElement& renderer, RenderStyle* style)
214 {
215     RenderElement& rendererForFirstLineStyle = renderer.isBeforeOrAfterContent() ? *renderer.parent() : const_cast<RenderElement&>(renderer);
216
217     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
218         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock()) {
219             if (type == Cached)
220                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
221             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == &renderer ? style : nullptr);
222         }
223     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
224         RenderStyle& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
225         if (&parentStyle != &rendererForFirstLineStyle.parent()->style()) {
226             if (type == Cached) {
227                 // A first-line style is in effect. Cache a first-line style for ourselves.
228                 rendererForFirstLineStyle.style().setHasPseudoStyle(FIRST_LINE_INHERITED);
229                 return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, &parentStyle);
230             }
231             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
232         }
233     }
234     return nullptr;
235 }
236
237 PassRefPtr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
238 {
239     if (!view().usesFirstLineRules())
240         return nullptr;
241
242     return firstLineStyleForCachedUncachedType(Uncached, *this, style);
243 }
244
245 RenderStyle* RenderElement::cachedFirstLineStyle() const
246 {
247     ASSERT(view().usesFirstLineRules());
248
249     RenderStyle& style = this->style();
250     if (RefPtr<RenderStyle> firstLineStyle = firstLineStyleForCachedUncachedType(Cached, *this, &style))
251         return firstLineStyle.get();
252
253     return &style;
254 }
255
256 RenderStyle& RenderElement::firstLineStyle() const
257 {
258     return view().usesFirstLineRules() ? *cachedFirstLineStyle() : style();
259 }
260
261 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
262 {
263     // If transform changed, and we are not composited, need to do a layout.
264     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
265         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
266         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
267             if (!hasLayer())
268                 diff = std::max(diff, StyleDifferenceLayout);
269             else {
270                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
271                 // then we actually need SimplifiedLayoutAndPositionedMovement.
272                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
273             }
274         
275         } else
276             diff = std::max(diff, StyleDifferenceRecompositeLayer);
277     }
278
279     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
280         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
281             diff = std::max(diff, StyleDifferenceRepaintLayer);
282         else
283             diff = std::max(diff, StyleDifferenceRecompositeLayer);
284     }
285
286     if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
287         if (hasLayer()
288             && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
289             && hasClipPath()
290             && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
291             diff = std::max(diff, StyleDifferenceRecompositeLayer);
292         else
293             diff = std::max(diff, StyleDifferenceRepaint);
294     }
295     
296     if (contextSensitiveProperties & ContextSensitivePropertyWillChange) {
297         if (style().willChange() && style().willChange()->canTriggerCompositing())
298             diff = std::max(diff, StyleDifferenceRecompositeLayer);
299     }
300     
301     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
302         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
303         if (!layer->isComposited() || layer->paintsWithFilters())
304             diff = std::max(diff, StyleDifferenceRepaintLayer);
305         else
306             diff = std::max(diff, StyleDifferenceRecompositeLayer);
307     }
308     
309     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
310     // style changing, since it depends on whether we decide to composite these elements. When the
311     // layer status of one of these elements changes, we need to force a layout.
312     if (diff < StyleDifferenceLayout && isRenderLayerModelObject()) {
313         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
314             diff = StyleDifferenceLayout;
315     }
316
317     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
318     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
319         diff = StyleDifferenceRepaint;
320
321     return diff;
322 }
323
324 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
325 {
326     for (auto& child : childrenOfType<RenderObject>(*this)) {
327         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
328             return true;
329         if (child.style().hasOutline() || child.style().hasBorder())
330             return true;
331     }
332     return false;
333 }
334
335 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
336 {
337     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
338 }
339
340 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
341 {
342     // Optimize the common case
343     if (FillLayer::imagesIdentical(oldLayers, newLayers))
344         return;
345     
346     // Go through the new layers and addClients first, to avoid removing all clients of an image.
347     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
348         if (currNew->image())
349             currNew->image()->addClient(this);
350     }
351
352     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
353         if (currOld->image())
354             currOld->image()->removeClient(this);
355     }
356 }
357
358 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
359 {
360     if (oldImage == newImage)
361         return;
362     if (oldImage)
363         oldImage->removeClient(this);
364     if (newImage)
365         newImage->addClient(this);
366 }
367
368 #if ENABLE(CSS_SHAPES)
369 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
370 {
371     if (oldShapeValue || newShapeValue)
372         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
373 }
374 #endif
375
376 void RenderElement::initializeStyle()
377 {
378     styleWillChange(StyleDifferenceNewStyle, style());
379
380     m_hasInitializedStyle = true;
381
382     updateFillImages(nullptr, m_style->backgroundLayers());
383     updateFillImages(nullptr, m_style->maskLayers());
384
385     updateImage(nullptr, m_style->borderImage().image());
386     updateImage(nullptr, m_style->maskBoxImage().image());
387
388 #if ENABLE(CSS_SHAPES)
389     updateShapeImage(nullptr, m_style->shapeOutside());
390 #endif
391
392     styleDidChange(StyleDifferenceNewStyle, nullptr);
393
394     // We shouldn't have any text children that would need styleDidChange at this point.
395     ASSERT(!childrenOfType<RenderText>(*this).first());
396
397     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
398     // have their parent set before getting a call to initializeStyle() :|
399 }
400
401 void RenderElement::setStyle(Ref<RenderStyle>&& style, StyleDifference minimalStyleDifference)
402 {
403     // FIXME: Should change RenderView so it can use initializeStyle too.
404     // If we do that, we can assert m_hasInitializedStyle unconditionally,
405     // and remove the check of m_hasInitializedStyle below too.
406     ASSERT(m_hasInitializedStyle || isRenderView());
407
408     if (m_style.ptr() == style.ptr() && minimalStyleDifference != StyleDifferenceEqual) {
409         // FIXME: Can we change things so we never hit this code path?
410         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
411         // style sharing is disabled for them. That should ensure that we never hit this code path.
412         ASSERT(!isRenderIFrame());
413         ASSERT(!isEmbeddedObject());
414         ASSERT(!isCanvas());
415         return;
416     }
417
418     StyleDifference diff = StyleDifferenceEqual;
419     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
420     if (m_hasInitializedStyle)
421         diff = m_style->diff(style.get(), contextSensitiveProperties);
422
423     diff = std::max(diff, minimalStyleDifference);
424
425     diff = adjustStyleDifference(diff, contextSensitiveProperties);
426
427     styleWillChange(diff, style.get());
428
429     Ref<RenderStyle> oldStyle(m_style.replace(WTFMove(style)));
430
431     updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
432     updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
433
434     updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
435     updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
436
437 #if ENABLE(CSS_SHAPES)
438     updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
439 #endif
440
441     bool doesNotNeedLayout = !parent();
442
443     styleDidChange(diff, oldStyle.ptr());
444
445     // Text renderers use their parent style. Notify them about the change.
446     for (auto& child : childrenOfType<RenderText>(*this))
447         child.styleDidChange(diff, oldStyle.ptr());
448
449     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
450     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
451     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
452     // in the future as we move renderer changes out of layout and into style changes.
453     if (doesNotNeedLayout)
454         return;
455
456     // Now that the layer (if any) has been updated, we need to adjust the diff again,
457     // check whether we should layout now, and decide if we need to repaint.
458     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
459     
460     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
461         if (updatedDiff == StyleDifferenceLayout)
462             setNeedsLayoutAndPrefWidthsRecalc();
463         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
464             setNeedsPositionedMovementLayout(oldStyle.ptr());
465         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
466             setNeedsPositionedMovementLayout(oldStyle.ptr());
467             setNeedsSimplifiedNormalFlowLayout();
468         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
469             setNeedsSimplifiedNormalFlowLayout();
470     }
471
472     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
473         // Do a repaint with the new style now, e.g., for example if we go from
474         // not having an outline to having an outline.
475         repaint();
476     }
477 }
478
479 bool RenderElement::childRequiresTable(const RenderObject& child) const
480 {
481     if (is<RenderTableCol>(child)) {
482         const RenderTableCol& newTableColumn = downcast<RenderTableCol>(child);
483         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
484         return !is<RenderTable>(*this) && !isColumnInColumnGroup;
485     }
486     if (is<RenderTableCaption>(child))
487         return !is<RenderTable>(*this);
488
489     if (is<RenderTableSection>(child))
490         return !is<RenderTable>(*this);
491
492     if (is<RenderTableRow>(child))
493         return !is<RenderTableSection>(*this);
494
495     if (is<RenderTableCell>(child))
496         return !is<RenderTableRow>(*this);
497
498     return false;
499 }
500
501 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
502 {
503     if (childRequiresTable(*newChild)) {
504         RenderTable* table;
505         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
506         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
507             table = downcast<RenderTable>(afterChild);
508         else {
509             table = RenderTable::createAnonymousWithParentRenderer(this);
510             addChild(table, beforeChild);
511         }
512         table->addChild(newChild);
513     } else
514         insertChildInternal(newChild, beforeChild, NotifyChildren);
515
516     if (is<RenderText>(*newChild))
517         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
518
519     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
520     // <g>s to have renderers - at least that's how our implementation works. Consider:
521     // <g display="none"><foreignObject><body style="position: relative">FOO...
522     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
523     // - when the document is painted, both layers are painted. The <body> layer doesn't
524     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
525     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
526     // and stop creating layers at all for these cases - they're not used anyways.
527     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
528         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
529
530     SVGRenderSupport::childAdded(*this, *newChild);
531 }
532
533 void RenderElement::removeChild(RenderObject& oldChild)
534 {
535     removeChildInternal(oldChild, NotifyChildren);
536 }
537
538 void RenderElement::destroyLeftoverChildren()
539 {
540     while (m_firstChild) {
541         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
542             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
543         } else {
544             // 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.
545             if (m_firstChild->node())
546                 m_firstChild->node()->setRenderer(nullptr);
547             m_firstChild->destroy();
548         }
549     }
550 }
551
552 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
553 {
554     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
555     ASSERT(!newChild->parent());
556     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
557
558     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
559         beforeChild = beforeChild->parent();
560
561     // This should never happen, but if it does prevent render tree corruption
562     // where child->parent() ends up being owner but child->nextSibling()->parent()
563     // is not owner.
564     if (beforeChild && beforeChild->parent() != this) {
565         ASSERT_NOT_REACHED();
566         return;
567     }
568
569     newChild->setParent(this);
570
571     if (m_firstChild == beforeChild)
572         m_firstChild = newChild;
573
574     if (beforeChild) {
575         RenderObject* previousSibling = beforeChild->previousSibling();
576         if (previousSibling)
577             previousSibling->setNextSibling(newChild);
578         newChild->setPreviousSibling(previousSibling);
579         newChild->setNextSibling(beforeChild);
580         beforeChild->setPreviousSibling(newChild);
581     } else {
582         if (lastChild())
583             lastChild()->setNextSibling(newChild);
584         newChild->setPreviousSibling(lastChild());
585         m_lastChild = newChild;
586     }
587
588     if (!documentBeingDestroyed()) {
589         if (notifyChildren == NotifyChildren)
590             newChild->insertedIntoTree();
591         if (is<RenderElement>(*newChild))
592             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
593     }
594
595     newChild->setNeedsLayoutAndPrefWidthsRecalc();
596     setPreferredLogicalWidthsDirty(true);
597     if (!normalChildNeedsLayout())
598         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
599
600     if (AXObjectCache* cache = document().axObjectCache())
601         cache->childrenChanged(this, newChild);
602     if (is<RenderBlockFlow>(*this))
603         downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
604     if (hasOutlineAutoAncestor() || outlineStyleForRepaint().outlineStyleIsAuto())
605         newChild->setHasOutlineAutoAncestor();
606 }
607
608 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
609 {
610     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
611     ASSERT(oldChild.parent() == this);
612
613     if (oldChild.isFloatingOrOutOfFlowPositioned())
614         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
615
616     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
617     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
618     // disappears gets repainted properly.
619     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
620         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
621         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
622         if (oldChild.isBody())
623             view().repaintRootContents();
624         else
625             oldChild.repaint();
626     }
627
628     // If we have a line box wrapper, delete it.
629     if (is<RenderBox>(oldChild))
630         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
631     else if (is<RenderLineBreak>(oldChild))
632         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
633
634     // If oldChild is the start or end of the selection, then clear the selection to
635     // avoid problems of invalid pointers.
636     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
637         frame().selection().setNeedsSelectionUpdate();
638
639     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
640         oldChild.willBeRemovedFromTree();
641
642     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
643     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
644     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
645     
646     RenderObject* nextSibling = oldChild.nextSibling();
647
648     if (oldChild.previousSibling())
649         oldChild.previousSibling()->setNextSibling(nextSibling);
650     if (nextSibling)
651         nextSibling->setPreviousSibling(oldChild.previousSibling());
652
653     if (m_firstChild == &oldChild)
654         m_firstChild = nextSibling;
655     if (m_lastChild == &oldChild)
656         m_lastChild = oldChild.previousSibling();
657
658     oldChild.setPreviousSibling(nullptr);
659     oldChild.setNextSibling(nullptr);
660     oldChild.setParent(nullptr);
661
662     // rendererRemovedFromTree walks the whole subtree. We can improve performance
663     // by skipping this step when destroying the entire tree.
664     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
665         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
666
667     if (AXObjectCache* cache = document().existingAXObjectCache())
668         cache->childrenChanged(this);
669 }
670
671 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
672 {
673     if (renderer.hasLayer()) {
674         if (!beforeChild && newObject) {
675             // We need to figure out the layer that follows newObject. We only do
676             // this the first time we find a child layer, and then we update the
677             // pointer values for newObject and beforeChild used by everyone else.
678             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
679             newObject = nullptr;
680         }
681         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
682         return;
683     }
684
685     for (auto& child : childrenOfType<RenderElement>(renderer))
686         addLayers(child, parentLayer, newObject, beforeChild);
687 }
688
689 void RenderElement::addLayers(RenderLayer* parentLayer)
690 {
691     if (!parentLayer)
692         return;
693
694     RenderElement* renderer = this;
695     RenderLayer* beforeChild = nullptr;
696     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
697 }
698
699 void RenderElement::removeLayers(RenderLayer* parentLayer)
700 {
701     if (!parentLayer)
702         return;
703
704     if (hasLayer()) {
705         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
706         return;
707     }
708
709     for (auto& child : childrenOfType<RenderElement>(*this))
710         child.removeLayers(parentLayer);
711 }
712
713 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
714 {
715     if (!newParent)
716         return;
717
718     if (hasLayer()) {
719         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
720         ASSERT(oldParent == layer->parent());
721         if (oldParent)
722             oldParent->removeChild(layer);
723         newParent->addChild(layer);
724         return;
725     }
726
727     for (auto& child : childrenOfType<RenderElement>(*this))
728         child.moveLayers(oldParent, newParent);
729 }
730
731 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
732 {
733     // Error check the parent layer passed in. If it's null, we can't find anything.
734     if (!parentLayer)
735         return nullptr;
736
737     // Step 1: If our layer is a child of the desired parent, then return our layer.
738     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
739     if (ourLayer && ourLayer->parent() == parentLayer)
740         return ourLayer;
741
742     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
743     // into our siblings trying to find the next layer whose parent is the desired parent.
744     if (!ourLayer || ourLayer == parentLayer) {
745         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
746             if (!is<RenderElement>(*child))
747                 continue;
748             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
749             if (nextLayer)
750                 return nextLayer;
751         }
752     }
753
754     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
755     // find anything.
756     if (parentLayer == ourLayer)
757         return nullptr;
758
759     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
760     // follow us to see if we can locate a layer.
761     if (checkParent && parent())
762         return parent()->findNextLayer(parentLayer, this, true);
763
764     return nullptr;
765 }
766
767 bool RenderElement::layerCreationAllowedForSubtree() const
768 {
769     RenderElement* parentRenderer = parent();
770     while (parentRenderer) {
771         if (parentRenderer->isSVGHiddenContainer())
772             return false;
773         parentRenderer = parentRenderer->parent();
774     }
775     
776     return true;
777 }
778
779 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
780 {
781     // FIXME: We could save this call when the change only affected non-inherited properties.
782     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
783         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
784             continue;
785
786         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
787             continue;
788
789 #if ENABLE(FULLSCREEN_API)
790         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
791             continue;
792 #endif
793
794         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
795         if (is<RenderFlowThread>(elementChild))
796             continue;
797
798         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
799         if (style().specifiesColumns()) {
800             if (elementChild.style().specifiesColumns())
801                 newStyle.get().inheritColumnPropertiesFrom(&style());
802             if (elementChild.style().columnSpan())
803                 newStyle.get().setColumnSpan(ColumnSpanAll);
804         }
805
806         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
807         // they contain block descendants of relative or sticky positioned inlines.
808         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
809             newStyle.get().setPosition(elementChild.style().position());
810
811         elementChild.setStyle(WTFMove(newStyle));
812     }
813 }
814
815 static inline bool rendererHasBackground(const RenderElement* renderer)
816 {
817     return renderer && renderer->hasBackground();
818 }
819
820 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
821 {
822     RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
823     if (oldStyle) {
824         // If our z-index changes value or our visibility changes,
825         // we need to dirty our stacking context's z-order list.
826         bool visibilityChanged = m_style->visibility() != newStyle.visibility()
827             || m_style->zIndex() != newStyle.zIndex()
828             || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
829 #if ENABLE(DASHBOARD_SUPPORT)
830         if (visibilityChanged)
831             document().setAnnotatedRegionsDirty(true);
832 #endif
833 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
834         if (visibilityChanged)
835             document().dirtyTouchEventRects();
836 #endif
837         if (visibilityChanged) {
838             if (AXObjectCache* cache = document().existingAXObjectCache())
839                 cache->childrenChanged(parent(), this);
840         }
841
842         // Keep layer hierarchy visibility bits up to date if visibility changes.
843         if (m_style->visibility() != newStyle.visibility()) {
844             if (RenderLayer* layer = enclosingLayer()) {
845                 if (newStyle.visibility() == VISIBLE)
846                     layer->setHasVisibleContent();
847                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
848                     layer->dirtyVisibleContentStatus();
849                     if (diff > StyleDifferenceRepaintLayer)
850                         repaint();
851                 }
852             }
853         }
854
855         if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
856             repaint();
857         if (isFloating() && (m_style->floating() != newStyle.floating()))
858             // For changes in float styles, we need to conceivably remove ourselves
859             // from the floating objects list.
860             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
861         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
862             // For changes in positioning styles, we need to conceivably remove ourselves
863             // from the positioned objects list.
864             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
865
866         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
867             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
868             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
869
870         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
871             && parent() && parent()->isRenderBlock();
872
873         // reset style flags
874         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
875             setFloating(false);
876             clearPositionedState();
877         }
878         setHorizontalWritingMode(true);
879         setHasBoxDecorations(false);
880         setHasOverflowClip(false);
881         setHasTransformRelatedProperty(false);
882         setHasReflection(false);
883     } else {
884         s_affectsParentBlock = false;
885         s_noLongerAffectsParentBlock = false;
886     }
887
888     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
889     bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
890     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
891         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
892
893         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
894         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
895         bool drawsRootBackground = isDocumentElementRenderer() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
896         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
897             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
898                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
899                     newStyleSlowScroll = false;
900
901                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
902                     oldStyleSlowScroll = false;
903             }
904         }
905
906         if (oldStyleSlowScroll != newStyleSlowScroll) {
907             if (oldStyleSlowScroll)
908                 view().frameView().removeSlowRepaintObject(this);
909
910             if (newStyleSlowScroll)
911                 view().frameView().addSlowRepaintObject(this);
912         }
913     }
914
915     if (isDocumentElementRenderer() || isBody())
916         view().frameView().updateExtendBackgroundIfNecessary();
917 }
918
919 void RenderElement::handleDynamicFloatPositionChange()
920 {
921     // We have gone from not affecting the inline status of the parent flow to suddenly
922     // having an impact.  See if there is a mismatch between the parent flow's
923     // childrenInline() state and our state.
924     setInline(style().isDisplayInlineType());
925     if (isInline() != parent()->childrenInline()) {
926         if (!isInline())
927             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
928         else {
929             // An anonymous block must be made to wrap this inline.
930             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
931             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
932             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
933             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
934         }
935     }
936 }
937
938 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
939 {
940     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
941     if (!parentBlock.canDropAnonymousBlockChild())
942         return;
943
944     // We have changed to floated or out-of-flow positioning so maybe all our parent's
945     // children can be inline now. Bail if there are any block children left on the line,
946     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
947     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
948     // if we find a continuation.
949     RenderObject* current = parent()->firstChild();
950     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
951         current = current->nextSibling();
952
953     if (current)
954         return;
955
956     RenderObject* next;
957     for (current = parent()->firstChild(); current; current = next) {
958         next = current->nextSibling();
959         if (current->isAnonymousBlock())
960             parentBlock.dropAnonymousBoxChild(parentBlock, downcast<RenderBlock>(*current));
961     }
962 }
963
964 #if !PLATFORM(IOS)
965 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
966 {
967     ASSERT(a->cursors() != b->cursors());
968     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
969 }
970
971 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
972 {
973     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
974 }
975 #endif
976
977 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
978 {
979     if (s_affectsParentBlock)
980         handleDynamicFloatPositionChange();
981
982     if (s_noLongerAffectsParentBlock) {
983         removeAnonymousWrappersForInlinesIfNecessary();
984         // Fresh floats need to be reparented if they actually belong to the previous anonymous block.
985         // It copies the logic of RenderBlock::addChildIgnoringContinuation
986         if (style().isFloating() && previousSibling() && previousSibling()->isAnonymousBlock())
987             downcast<RenderBoxModelObject>(*parent()).moveChildTo(&downcast<RenderBoxModelObject>(*previousSibling()), this);
988     }
989
990     SVGRenderSupport::styleChanged(*this, oldStyle);
991
992     if (!m_parent)
993         return;
994     
995     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
996         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
997
998         // If the object already needs layout, then setNeedsLayout won't do
999         // any work. But if the containing block has changed, then we may need
1000         // to mark the new containing blocks for layout. The change that can
1001         // directly affect the containing block of this object is a change to
1002         // the position style.
1003         if (needsLayout() && oldStyle->position() != m_style->position())
1004             markContainingBlocksForLayout();
1005
1006         if (diff == StyleDifferenceLayout)
1007             setNeedsLayoutAndPrefWidthsRecalc();
1008         else
1009             setNeedsSimplifiedNormalFlowLayout();
1010     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1011         setNeedsPositionedMovementLayout(oldStyle);
1012         setNeedsSimplifiedNormalFlowLayout();
1013     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1014         setNeedsPositionedMovementLayout(oldStyle);
1015
1016     // Don't check for repaint here; we need to wait until the layer has been
1017     // updated by subclasses before we know if we have to repaint (in setStyle()).
1018
1019 #if !PLATFORM(IOS)
1020     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1021         frame().eventHandler().scheduleCursorUpdate();
1022 #endif
1023     bool hadOutlineAuto = oldStyle && oldStyle->outlineStyleIsAuto();
1024     bool hasOutlineAuto = outlineStyleForRepaint().outlineStyleIsAuto();
1025     if (hasOutlineAuto != hadOutlineAuto) {
1026         updateOutlineAutoAncestor(hasOutlineAuto);
1027         issueRepaintForOutlineAuto(hasOutlineAuto ? outlineStyleForRepaint().outlineSize() : oldStyle->outlineSize());
1028     }
1029 }
1030
1031 void RenderElement::insertedIntoTree()
1032 {
1033     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1034         containerFlowThread->addFlowChild(*this);
1035
1036     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1037     // and don't have a layer attached to ourselves.
1038     RenderLayer* layer = nullptr;
1039     if (firstChild() || hasLayer()) {
1040         layer = parent()->enclosingLayer();
1041         addLayers(layer);
1042     }
1043
1044     // If |this| is visible but this object was not, tell the layer it has some visible content
1045     // that needs to be drawn and layer visibility optimization can't be used
1046     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1047         if (!layer)
1048             layer = parent()->enclosingLayer();
1049         if (layer)
1050             layer->setHasVisibleContent();
1051     }
1052
1053     RenderObject::insertedIntoTree();
1054 }
1055
1056 void RenderElement::willBeRemovedFromTree()
1057 {
1058     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1059     RenderLayer* layer = nullptr;
1060     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1061         if ((layer = parent()->enclosingLayer()))
1062             layer->dirtyVisibleContentStatus();
1063     }
1064     // Keep our layer hierarchy updated.
1065     if (firstChild() || hasLayer()) {
1066         if (!layer)
1067             layer = parent()->enclosingLayer();
1068         removeLayers(layer);
1069     }
1070
1071     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1072         view().frameView().removeSlowRepaintObject(this);
1073
1074     if (isOutOfFlowPositioned() && parent()->childrenInline())
1075         parent()->dirtyLinesFromChangedChild(*this);
1076
1077     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1078         containerFlowThread->removeFlowChild(*this);
1079
1080     RenderObject::willBeRemovedFromTree();
1081 }
1082
1083 inline void RenderElement::clearLayoutRootIfNeeded() const
1084 {
1085     if (documentBeingDestroyed())
1086         return;
1087
1088     if (view().frameView().layoutRoot() != this)
1089         return;
1090
1091     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
1092     // which ensures that this renderer is no longer the layout root.
1093     ASSERT_NOT_REACHED();
1094     
1095     // This indicates a failure to layout the child, which is why
1096     // the layout root is still set to |this|. Make sure to clear it
1097     // since we are getting destroyed.
1098     view().frameView().clearLayoutRoot();
1099 }
1100
1101 void RenderElement::willBeDestroyed()
1102 {
1103     animation().cancelAnimations(*this);
1104
1105     destroyLeftoverChildren();
1106
1107     if (hasCounterNodeMap())
1108         RenderCounter::destroyCounterNodes(*this);
1109
1110     RenderObject::willBeDestroyed();
1111
1112 #if !ASSERT_DISABLED
1113     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1114         // After remove, the object and the associated information should not be in any flow thread.
1115         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1116             ASSERT(!flowThread->hasChild(*this));
1117             ASSERT(!flowThread->hasChildInfo(this));
1118         }
1119     }
1120 #endif
1121     clearLayoutRootIfNeeded();
1122 }
1123
1124 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1125 {
1126     ASSERT(!isSetNeedsLayoutForbidden());
1127     if (needsPositionedMovementLayout())
1128         return;
1129     setNeedsPositionedMovementLayoutBit(true);
1130     markContainingBlocksForLayout();
1131     if (hasLayer()) {
1132         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1133             setLayerNeedsFullRepaint();
1134         else
1135             setLayerNeedsFullRepaintForPositionedMovementLayout();
1136     }
1137 }
1138
1139 void RenderElement::clearChildNeedsLayout()
1140 {
1141     setNormalChildNeedsLayoutBit(false);
1142     setPosChildNeedsLayoutBit(false);
1143     setNeedsSimplifiedNormalFlowLayoutBit(false);
1144     setNormalChildNeedsLayoutBit(false);
1145     setNeedsPositionedMovementLayoutBit(false);
1146 }
1147
1148 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1149 {
1150     ASSERT(!isSetNeedsLayoutForbidden());
1151     if (needsSimplifiedNormalFlowLayout())
1152         return;
1153     setNeedsSimplifiedNormalFlowLayoutBit(true);
1154     markContainingBlocksForLayout();
1155     if (hasLayer())
1156         setLayerNeedsFullRepaint();
1157 }
1158
1159 RenderElement& RenderElement::rendererForRootBackground()
1160 {
1161     ASSERT(isDocumentElementRenderer());
1162     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1163         // Locate the <body> element using the DOM. This is easier than trying
1164         // to crawl around a render tree with potential :before/:after content and
1165         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1166         // render object very easily via the DOM.
1167         if (auto* body = document().body()) {
1168             if (auto* renderer = body->renderer())
1169                 return *renderer;
1170         }
1171     }
1172     return *this;
1173 }
1174
1175 RenderElement* RenderElement::hoverAncestor() const
1176 {
1177     // When searching for the hover ancestor and encountering a named flow thread,
1178     // the search will continue with the DOM ancestor of the top-most element
1179     // in the named flow thread.
1180     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1181     RenderElement* hoverAncestor = parent();
1182
1183     // Skip anonymous blocks directly flowed into flow threads as it would
1184     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1185     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1186         hoverAncestor = hoverAncestor->parent();
1187
1188     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1189         hoverAncestor = nullptr;
1190         if (Element* element = this->element()) {
1191             if (auto parent = element->parentNode())
1192                 hoverAncestor = parent->renderer();
1193         }
1194     }
1195
1196     return hoverAncestor;
1197 }
1198
1199 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1200 {
1201     paintInfo.phase = phase;
1202     element.paint(paintInfo, childPoint);
1203 }
1204
1205 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1206 {
1207     // Paint all phases atomically, as though the element established its own stacking context.
1208     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1209     // This is also used by other elements (e.g. flex items and grid items).
1210     if (paintInfo.phase == PaintPhaseSelection) {
1211         paint(paintInfo, childPoint);
1212     } else if (paintInfo.phase == PaintPhaseForeground) {
1213         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1214         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1215         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1216         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1217         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1218
1219         // Reset |paintInfo| to the original phase.
1220         paintInfo.phase = PaintPhaseForeground;
1221     }
1222 }
1223
1224 void RenderElement::layout()
1225 {
1226     StackStats::LayoutCheckPoint layoutCheckPoint;
1227     ASSERT(needsLayout());
1228     RenderObject* child = firstChild();
1229     while (child) {
1230         if (child->needsLayout())
1231             downcast<RenderElement>(*child).layout();
1232         ASSERT(!child->needsLayout());
1233         child = child->nextSibling();
1234     }
1235     clearNeedsLayout();
1236 }
1237
1238 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1239 {
1240     // Nobody will use multiple layers without wanting fancy positioning.
1241     if (layer->next())
1242         return true;
1243
1244     // Make sure we have a valid image.
1245     StyleImage* image = layer->image();
1246     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1247         return false;
1248
1249     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1250         return true;
1251
1252     EFillSizeType sizeType = layer->sizeType();
1253
1254     if (sizeType == Contain || sizeType == Cover)
1255         return true;
1256
1257     if (sizeType == SizeLength) {
1258         LengthSize size = layer->sizeLength();
1259         if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1260             return true;
1261         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1262         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1263             return true;
1264     } else if (image->usesImageContainerSize())
1265         return true;
1266
1267     return false;
1268 }
1269
1270 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1271 {
1272     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1273         return true;
1274
1275     // If we don't have a background/border/mask, then nothing to do.
1276     if (!renderer.hasBoxDecorations())
1277         return false;
1278
1279     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1280         return true;
1281
1282     // Our fill layers are ok. Let's check border.
1283     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1284         return true;
1285
1286     return false;
1287 }
1288
1289 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1290 {
1291     if (view().printing())
1292         return false; // Don't repaint if we're printing.
1293
1294     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1295     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1296     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1297     LayoutRect newOutlineBox;
1298
1299     bool fullRepaint = selfNeedsLayout();
1300     // Presumably a background or a border exists if border-fit:lines was specified.
1301     if (!fullRepaint && style().borderFit() == BorderFitLines)
1302         fullRepaint = true;
1303     if (!fullRepaint) {
1304         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1305         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1306         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1307         fullRepaint = (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)));
1308     }
1309
1310     if (!repaintContainer)
1311         repaintContainer = &view();
1312
1313     if (fullRepaint) {
1314         repaintUsingContainer(repaintContainer, oldBounds);
1315         if (newBounds != oldBounds)
1316             repaintUsingContainer(repaintContainer, newBounds);
1317         return true;
1318     }
1319
1320     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1321         return false;
1322
1323     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1324     if (deltaLeft > 0)
1325         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1326     else if (deltaLeft < 0)
1327         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1328
1329     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1330     if (deltaRight > 0)
1331         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1332     else if (deltaRight < 0)
1333         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1334
1335     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1336     if (deltaTop > 0)
1337         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1338     else if (deltaTop < 0)
1339         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1340
1341     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1342     if (deltaBottom > 0)
1343         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1344     else if (deltaBottom < 0)
1345         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1346
1347     if (newOutlineBox == oldOutlineBox)
1348         return false;
1349
1350     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1351     // two rectangles (but typically only one).
1352     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1353     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1354     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1355     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1356     if (width) {
1357         LayoutUnit shadowLeft;
1358         LayoutUnit shadowRight;
1359         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1360         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1361         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1362         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1363         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1364         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1365         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1366             newOutlineBox.y(),
1367             width + decorationsWidth,
1368             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1369         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1370         if (rightRect.x() < right) {
1371             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1372             repaintUsingContainer(repaintContainer, rightRect);
1373         }
1374     }
1375     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1376     if (height) {
1377         LayoutUnit shadowTop;
1378         LayoutUnit shadowBottom;
1379         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1380         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1381         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1382         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1383         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1384             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1385         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1386         LayoutRect bottomRect(newOutlineBox.x(),
1387             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1388             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1389             height + decorationsHeight);
1390         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1391         if (bottomRect.y() < bottom) {
1392             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1393             repaintUsingContainer(repaintContainer, bottomRect);
1394         }
1395     }
1396     return false;
1397 }
1398
1399 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1400 {
1401     ASSERT(style().hasBorder());
1402
1403     StyleImage* borderImage = style().borderImage().image();
1404     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1405 }
1406
1407 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1408 {
1409     auto& frameView = view().frameView();
1410     if (frameView.isOffscreen())
1411         return false;
1412
1413     if (!hasOverflowClip()) {
1414         // FIXME: Computing the overflow rect is expensive if any descendant has
1415         // its own self-painting layer. As a result, we prefer to abort early in
1416         // this case and assume it may cause us to repaint inside the viewport.
1417         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1418             return true;
1419     }
1420
1421     // Compute viewport rect if it was not provided.
1422     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1423     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1424 }
1425
1426 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1427 {
1428     const Document& document = renderer.document();
1429     if (document.inPageCache())
1430         return false;
1431     if (document.activeDOMObjectsAreSuspended())
1432         return false;
1433     if (renderer.style().visibility() != VISIBLE)
1434         return false;
1435     if (renderer.view().frameView().isOffscreen())
1436         return false;
1437
1438     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1439     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1440     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1441     // can no longer check if it is a background image.
1442     bool backgroundIsPaintedByRoot = renderer.isDocumentElementRenderer();
1443     if (renderer.isBody()) {
1444         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1445         ASSERT(rootRenderer.isDocumentElementRenderer());
1446         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1447         // FIXME: Should share body background propagation code.
1448         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1449
1450     }
1451     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect() : renderer.absoluteClippedOverflowRect();
1452     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1453         return false;
1454
1455     return true;
1456 }
1457
1458 void RenderElement::registerForVisibleInViewportCallback()
1459 {
1460     if (isRegisteredForVisibleInViewportCallback())
1461         return;
1462     setIsRegisteredForVisibleInViewportCallback(true);
1463
1464     view().registerForVisibleInViewportCallback(*this);
1465 }
1466
1467 void RenderElement::unregisterForVisibleInViewportCallback()
1468 {
1469     if (!isRegisteredForVisibleInViewportCallback())
1470         return;
1471     setIsRegisteredForVisibleInViewportCallback(false);
1472
1473     view().unregisterForVisibleInViewportCallback(*this);
1474     m_visibleInViewportState = VisibilityUnknown;
1475 }
1476
1477 void RenderElement::visibleInViewportStateChanged(VisibleInViewportState state)
1478 {
1479     if (state == visibleInViewportState())
1480         return;
1481     setVisibleInViewportState(state);
1482
1483     if (element())
1484         element()->isVisibleInViewportChanged();
1485 }
1486
1487 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1488 {
1489     if (document().inPageCache())
1490         return;
1491     auto& frameView = view().frameView();
1492     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1493     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1494         // FIXME: It would be better to pass the image along with the renderer
1495         // so that we can be smarter about detecting if the image is inside the
1496         // viewport in repaintForPausedImageAnimationsIfNeeded().
1497         view().addRendererWithPausedImageAnimations(*this);
1498         return;
1499     }
1500     imageChanged(&image);
1501 }
1502
1503 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1504 {
1505     ASSERT(m_hasPausedImageAnimations);
1506     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1507         return false;
1508
1509     repaint();
1510
1511     // For directly-composited animated GIFs it does not suffice to call repaint() to resume animation. We need to mark the image as changed.
1512     if (is<RenderBoxModelObject>(*this))
1513         downcast<RenderBoxModelObject>(*this).contentChanged(ImageChanged);
1514
1515     return true;
1516 }
1517
1518 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1519 {
1520     auto* renderer = this;
1521     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1522         renderer = renderer->parent();
1523     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1524 }
1525
1526 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1527 {
1528     return controlStatesRendererMap().contains(o);
1529 }
1530
1531 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1532 {
1533     return controlStatesRendererMap().get(o);
1534 }
1535
1536 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1537 {
1538     ControlStates* states = controlStatesRendererMap().get(o);
1539     if (states) {
1540         controlStatesRendererMap().remove(o);
1541         delete states;
1542     }
1543 }
1544
1545 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1546 {
1547     controlStatesRendererMap().add(o, states);
1548 }
1549
1550 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1551 {
1552     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1553         return nullptr;
1554
1555     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1556     if (cachedStyle)
1557         return cachedStyle;
1558
1559     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1560     if (result)
1561         return style().addCachedPseudoStyle(result.release());
1562     return nullptr;
1563 }
1564
1565 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1566 {
1567     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1568         return nullptr;
1569
1570     if (!parentStyle) {
1571         ASSERT(!ownStyle);
1572         parentStyle = &style();
1573     }
1574
1575     if (isAnonymous())
1576         return nullptr;
1577
1578     auto& styleResolver = element()->styleResolver();
1579
1580     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1581         auto result = styleResolver.styleForElement(*element(), parentStyle).renderStyle;
1582         result->setStyleType(FIRST_LINE_INHERITED);
1583         return WTFMove(result);
1584     }
1585
1586     return styleResolver.pseudoStyleForElement(*element(), pseudoStyleRequest, *parentStyle);
1587 }
1588
1589 Color RenderElement::selectionColor(int colorProperty) const
1590 {
1591     // If the element is unselectable, or we are only painting the selection,
1592     // don't override the foreground color with the selection foreground color.
1593     if (style().userSelect() == SELECT_NONE
1594         || (view().frameView().paintBehavior() & (PaintBehaviorSelectionOnly | PaintBehaviorSelectionAndBackgroundsOnly)))
1595         return Color();
1596
1597     if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1598         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1599         if (!color.isValid())
1600             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1601         return color;
1602     }
1603
1604     if (frame().selection().isFocusedAndActive())
1605         return theme().activeSelectionForegroundColor();
1606     return theme().inactiveSelectionForegroundColor();
1607 }
1608
1609 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1610 {
1611     if (isAnonymous())
1612         return nullptr;
1613
1614     if (ShadowRoot* root = element()->containingShadowRoot()) {
1615         if (root->type() == ShadowRoot::Type::UserAgent) {
1616             if (Element* shadowHost = element()->shadowHost())
1617                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1618         }
1619     }
1620
1621     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1622 }
1623
1624 Color RenderElement::selectionForegroundColor() const
1625 {
1626     return selectionColor(CSSPropertyWebkitTextFillColor);
1627 }
1628
1629 Color RenderElement::selectionEmphasisMarkColor() const
1630 {
1631     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1632 }
1633
1634 Color RenderElement::selectionBackgroundColor() const
1635 {
1636     if (style().userSelect() == SELECT_NONE)
1637         return Color();
1638
1639     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1640         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1641
1642     RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1643     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1644         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1645
1646     if (frame().selection().isFocusedAndActive())
1647         return theme().activeSelectionBackgroundColor();
1648     return theme().inactiveSelectionBackgroundColor();
1649 }
1650
1651 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1652 {
1653     if (!isInline() || isReplaced()) {
1654         point = localToAbsolute(FloatPoint(), UseTransforms);
1655         return true;
1656     }
1657
1658     // find the next text/image child, to get a position
1659     const RenderObject* o = this;
1660     while (o) {
1661         const RenderObject* p = o;
1662         if (RenderObject* child = o->firstChildSlow())
1663             o = child;
1664         else if (o->nextSibling())
1665             o = o->nextSibling();
1666         else {
1667             RenderObject* next = 0;
1668             while (!next && o->parent()) {
1669                 o = o->parent();
1670                 next = o->nextSibling();
1671             }
1672             o = next;
1673
1674             if (!o)
1675                 break;
1676         }
1677         ASSERT(o);
1678
1679         if (!o->isInline() || o->isReplaced()) {
1680             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1681             return true;
1682         }
1683
1684         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1685             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1686         } else if (is<RenderText>(*o) || o->isReplaced()) {
1687             point = FloatPoint();
1688             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1689                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1690             else if (is<RenderBox>(*o))
1691                 point.moveBy(downcast<RenderBox>(*o).location());
1692             point = o->container()->localToAbsolute(point, UseTransforms);
1693             return true;
1694         }
1695     }
1696     
1697     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1698     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1699     if (!o && document().view()) {
1700         point = FloatPoint(0, document().view()->contentsHeight());
1701         return true;
1702     }
1703     return false;
1704 }
1705
1706 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1707 {
1708     if (!isInline() || isReplaced()) {
1709         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1710         return true;
1711     }
1712
1713     // find the last text/image child, to get a position
1714     const RenderObject* o = this;
1715     while (o) {
1716         if (RenderObject* child = o->lastChildSlow())
1717             o = child;
1718         else if (o->previousSibling())
1719             o = o->previousSibling();
1720         else {
1721             RenderObject* prev = 0;
1722             while (!prev) {
1723                 o = o->parent();
1724                 if (!o)
1725                     return false;
1726                 prev = o->previousSibling();
1727             }
1728             o = prev;
1729         }
1730         ASSERT(o);
1731         if (is<RenderText>(*o) || o->isReplaced()) {
1732             point = FloatPoint();
1733             if (is<RenderText>(*o)) {
1734                 LayoutRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1735                 if (!linesBox.maxX() && !linesBox.maxY())
1736                     continue;
1737                 point.moveBy(linesBox.maxXMaxYCorner());
1738             } else
1739                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1740             point = o->container()->localToAbsolute(point, UseTransforms);
1741             return true;
1742         }
1743     }
1744     return true;
1745 }
1746
1747 LayoutRect RenderElement::anchorRect() const
1748 {
1749     FloatPoint leading, trailing;
1750     getLeadingCorner(leading);
1751     getTrailingCorner(trailing);
1752
1753     FloatPoint upperLeft = leading;
1754     FloatPoint lowerRight = trailing;
1755
1756     // Vertical writing modes might mean the leading point is not in the top left
1757     if (!isInline() || isReplaced()) {
1758         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1759         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1760     } // Otherwise, it's not obvious what to do.
1761
1762     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1763 }
1764
1765 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1766 {
1767     const RenderElement* current = this;
1768     do {
1769         if (current->isRenderBlock())
1770             return current;
1771         if (!current->isRenderInline() || current->isRubyText())
1772             return nullptr;
1773         
1774         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1775         if (styleToUse.textDecoration() & textDecoration)
1776             return current;
1777         current = current->parent();
1778     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1779
1780     return current;
1781 }
1782
1783 void RenderElement::drawLineForBoxSide(GraphicsContext& graphicsContext, const FloatRect& rect, BoxSide side, Color color, EBorderStyle borderStyle, float adjacentWidth1, float adjacentWidth2, bool antialias) const
1784 {
1785     auto drawBorderRect = [&graphicsContext] (const FloatRect& rect)
1786     {
1787         if (rect.isEmpty())
1788             return;
1789         graphicsContext.drawRect(rect);
1790     };
1791
1792     auto drawLineFor = [this, &graphicsContext, color, antialias] (const FloatRect& rect, BoxSide side, EBorderStyle borderStyle, const FloatSize& adjacent)
1793     {
1794         if (rect.isEmpty())
1795             return;
1796         drawLineForBoxSide(graphicsContext, rect, side, color, borderStyle, adjacent.width(), adjacent.height(), antialias);
1797     };
1798
1799     float x1 = rect.x();
1800     float x2 = rect.maxX();
1801     float y1 = rect.y();
1802     float y2 = rect.maxY();
1803     float thickness;
1804     float length;
1805     if (side == BSTop || side == BSBottom) {
1806         thickness = y2 - y1;
1807         length = x2 - x1;
1808     } else {
1809         thickness = x2 - x1;
1810         length = y2 - y1;
1811     }
1812     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
1813     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
1814     if (!thickness || !length)
1815         return;
1816
1817     float deviceScaleFactor = document().deviceScaleFactor();
1818     if (borderStyle == DOUBLE && (thickness * deviceScaleFactor) < 3)
1819         borderStyle = SOLID;
1820
1821     switch (borderStyle) {
1822     case BNONE:
1823     case BHIDDEN:
1824         return;
1825     case DOTTED:
1826     case DASHED: {
1827         bool wasAntialiased = graphicsContext.shouldAntialias();
1828         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1829         graphicsContext.setShouldAntialias(antialias);
1830         graphicsContext.setStrokeColor(color);
1831         graphicsContext.setStrokeThickness(thickness);
1832         graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1833         graphicsContext.drawLine(roundPointToDevicePixels(LayoutPoint(x1, y1), deviceScaleFactor), roundPointToDevicePixels(LayoutPoint(x2, y2), deviceScaleFactor));
1834         graphicsContext.setShouldAntialias(wasAntialiased);
1835         graphicsContext.setStrokeStyle(oldStrokeStyle);
1836         break;
1837     }
1838     case DOUBLE: {
1839         float thirdOfThickness = ceilToDevicePixel(thickness / 3, deviceScaleFactor);
1840         ASSERT(thirdOfThickness);
1841
1842         if (!adjacentWidth1 && !adjacentWidth2) {
1843             StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1844             graphicsContext.setStrokeStyle(NoStroke);
1845             graphicsContext.setFillColor(color);
1846
1847             bool wasAntialiased = graphicsContext.shouldAntialias();
1848             graphicsContext.setShouldAntialias(antialias);
1849
1850             switch (side) {
1851             case BSTop:
1852             case BSBottom:
1853                 drawBorderRect(snapRectToDevicePixels(x1, y1, length, thirdOfThickness, deviceScaleFactor));
1854                 drawBorderRect(snapRectToDevicePixels(x1, y2 - thirdOfThickness, length, thirdOfThickness, deviceScaleFactor));
1855                 break;
1856             case BSLeft:
1857             case BSRight:
1858                 drawBorderRect(snapRectToDevicePixels(x1, y1, thirdOfThickness, length, deviceScaleFactor));
1859                 drawBorderRect(snapRectToDevicePixels(x2 - thirdOfThickness, y1, thirdOfThickness, length, deviceScaleFactor));
1860                 break;
1861             }
1862
1863             graphicsContext.setShouldAntialias(wasAntialiased);
1864             graphicsContext.setStrokeStyle(oldStrokeStyle);
1865         } else {
1866             float adjacent1BigThird = ceilToDevicePixel(adjacentWidth1 / 3, deviceScaleFactor);
1867             float adjacent2BigThird = ceilToDevicePixel(adjacentWidth2 / 3, deviceScaleFactor);
1868
1869             float offset1 = floorToDevicePixel(fabs(adjacentWidth1) * 2 / 3, deviceScaleFactor);
1870             float offset2 = floorToDevicePixel(fabs(adjacentWidth2) * 2 / 3, deviceScaleFactor);
1871
1872             float mitreOffset1 = adjacentWidth1 < 0 ? offset1 : 0;
1873             float mitreOffset2 = adjacentWidth1 > 0 ? offset1 : 0;
1874             float mitreOffset3 = adjacentWidth2 < 0 ? offset2 : 0;
1875             float mitreOffset4 = adjacentWidth2 > 0 ? offset2 : 0;
1876
1877             FloatRect paintBorderRect;
1878             switch (side) {
1879             case BSTop:
1880                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y1, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1881                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1882
1883                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y2 - thirdOfThickness, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1884                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1885                 break;
1886             case BSLeft:
1887                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1888                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1889
1890                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1891                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1892                 break;
1893             case BSBottom:
1894                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y1, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1895                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1896
1897                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y2 - thirdOfThickness, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1898                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1899                 break;
1900             case BSRight:
1901                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1902                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1903
1904                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1905                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1906                 break;
1907             default:
1908                 break;
1909             }
1910         }
1911         break;
1912     }
1913     case RIDGE:
1914     case GROOVE: {
1915         EBorderStyle s1;
1916         EBorderStyle s2;
1917         if (borderStyle == GROOVE) {
1918             s1 = INSET;
1919             s2 = OUTSET;
1920         } else {
1921             s1 = OUTSET;
1922             s2 = INSET;
1923         }
1924
1925         float adjacent1BigHalf = ceilToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1926         float adjacent2BigHalf = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1927
1928         float adjacent1SmallHalf = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1929         float adjacent2SmallHalf = floorToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1930
1931         float offset1 = 0;
1932         float offset2 = 0;
1933         float offset3 = 0;
1934         float offset4 = 0;
1935
1936         if (((side == BSTop || side == BSLeft) && adjacentWidth1 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 > 0))
1937             offset1 = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1938
1939         if (((side == BSTop || side == BSLeft) && adjacentWidth2 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 > 0))
1940             offset2 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1941
1942         if (((side == BSTop || side == BSLeft) && adjacentWidth1 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 < 0))
1943             offset3 = floorToDevicePixel(fabs(adjacentWidth1) / 2, deviceScaleFactor);
1944
1945         if (((side == BSTop || side == BSLeft) && adjacentWidth2 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 < 0))
1946             offset4 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1947
1948         float adjustedX = ceilToDevicePixel((x1 + x2) / 2, deviceScaleFactor);
1949         float adjustedY = ceilToDevicePixel((y1 + y2) / 2, deviceScaleFactor);
1950         // Quads can't use the default snapping rect functions.
1951         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1952         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1953         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1954         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1955
1956         switch (side) {
1957         case BSTop:
1958             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1959             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1960             break;
1961         case BSLeft:
1962             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1963             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1964             break;
1965         case BSBottom:
1966             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1967             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1968             break;
1969         case BSRight:
1970             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1971             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1972             break;
1973         }
1974         break;
1975     }
1976     case INSET:
1977     case OUTSET:
1978         calculateBorderStyleColor(borderStyle, side, color);
1979         FALLTHROUGH;
1980     case SOLID: {
1981         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1982         ASSERT(x2 >= x1);
1983         ASSERT(y2 >= y1);
1984         if (!adjacentWidth1 && !adjacentWidth2) {
1985             graphicsContext.setStrokeStyle(NoStroke);
1986             graphicsContext.setFillColor(color);
1987             bool wasAntialiased = graphicsContext.shouldAntialias();
1988             graphicsContext.setShouldAntialias(antialias);
1989             drawBorderRect(snapRectToDevicePixels(x1, y1, x2 - x1, y2 - y1, deviceScaleFactor));
1990             graphicsContext.setShouldAntialias(wasAntialiased);
1991             graphicsContext.setStrokeStyle(oldStrokeStyle);
1992             return;
1993         }
1994
1995         // FIXME: These roundings should be replaced by ASSERT(device pixel positioned) when all the callers have transitioned to device pixels.
1996         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1997         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1998         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1999         y2 = roundToDevicePixel(y2, deviceScaleFactor);
2000
2001         Vector<FloatPoint> quad;
2002         quad.reserveInitialCapacity(4);
2003         switch (side) {
2004         case BSTop:
2005             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y1 });
2006             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y2 });
2007             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y2 });
2008             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y1 });
2009             break;
2010         case BSBottom:
2011             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y1 });
2012             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y2 });
2013             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y2 });
2014             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y1 });
2015             break;
2016         case BSLeft:
2017             quad.uncheckedAppend({ x1, y1 + std::max<float>(-adjacentWidth1, 0) });
2018             quad.uncheckedAppend({ x1, y2 - std::max<float>(-adjacentWidth2, 0) });
2019             quad.uncheckedAppend({ x2, y2 - std::max<float>( adjacentWidth2, 0) });
2020             quad.uncheckedAppend({ x2, y1 + std::max<float>( adjacentWidth1, 0) });
2021             break;
2022         case BSRight:
2023             quad.uncheckedAppend({ x1, y1 + std::max<float>( adjacentWidth1, 0) });
2024             quad.uncheckedAppend({ x1, y2 - std::max<float>( adjacentWidth2, 0) });
2025             quad.uncheckedAppend({ x2, y2 - std::max<float>(-adjacentWidth2, 0) });
2026             quad.uncheckedAppend({ x2, y1 + std::max<float>(-adjacentWidth1, 0) });
2027             break;
2028         }
2029
2030         graphicsContext.setStrokeStyle(NoStroke);
2031         graphicsContext.setFillColor(color);
2032         bool wasAntialiased = graphicsContext.shouldAntialias();
2033         graphicsContext.setShouldAntialias(antialias);
2034         graphicsContext.fillPath(Path::polygonPathFromPoints(quad));
2035         graphicsContext.setShouldAntialias(wasAntialiased);
2036
2037         graphicsContext.setStrokeStyle(oldStrokeStyle);
2038         break;
2039     }
2040     }
2041 }
2042
2043 void RenderElement::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, const RenderStyle& style)
2044 {
2045     ASSERT(style.outlineStyleIsAuto());
2046
2047     Vector<LayoutRect> focusRingRects;
2048     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
2049     float outlineOffset = style.outlineOffset();
2050     Vector<FloatRect> pixelSnappedFocusRingRects;
2051     float deviceScaleFactor = document().deviceScaleFactor();
2052     for (auto rect : focusRingRects) {
2053         rect.inflate(outlineOffset);
2054         pixelSnappedFocusRingRects.append(snapRectToDevicePixels(rect, deviceScaleFactor));
2055     }
2056 #if PLATFORM(MAC)
2057     bool needsRepaint;
2058     if (style.hasBorderRadius()) {
2059         Path path = PathUtilities::pathWithShrinkWrappedRectsForOutline(pixelSnappedFocusRingRects, style.border(), outlineOffset, style.direction(), style.writingMode(),
2060             document().deviceScaleFactor());
2061         if (path.isEmpty()) {
2062             for (auto rect : pixelSnappedFocusRingRects)
2063                 path.addRect(rect);
2064         }
2065         paintInfo.context().drawFocusRing(path, document().page()->focusController().timeSinceFocusWasSet(), needsRepaint);
2066     } else
2067         paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, document().page()->focusController().timeSinceFocusWasSet(), needsRepaint);
2068     if (needsRepaint)
2069         document().page()->focusController().setFocusedElementNeedsRepaint();
2070 #else
2071     paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, style.outlineWidth(), style.outlineOffset(), style.visitedDependentColor(CSSPropertyOutlineColor));
2072 #endif
2073 }
2074
2075 void RenderElement::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
2076 {
2077     GraphicsContext& graphicsContext = paintInfo.context();
2078     if (graphicsContext.paintingDisabled())
2079         return;
2080
2081     if (!hasOutline())
2082         return;
2083
2084     RenderStyle& styleToUse = style();
2085     float outlineWidth = floorToDevicePixel(styleToUse.outlineWidth(), document().deviceScaleFactor());
2086     float outlineOffset = floorToDevicePixel(styleToUse.outlineOffset(), document().deviceScaleFactor());
2087
2088     // Only paint the focus ring by hand if the theme isn't able to draw it.
2089     if (styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
2090         paintFocusRing(paintInfo, paintRect.location(), styleToUse);
2091
2092     if (hasOutlineAnnotation() && !styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
2093         addPDFURLRect(paintInfo, paintRect.location());
2094
2095     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
2096         return;
2097
2098     FloatRect outer = paintRect;
2099     outer.inflate(outlineOffset + outlineWidth);
2100     FloatRect inner = outer;
2101     inner.inflate(-outlineWidth);
2102
2103     // FIXME: This prevents outlines from painting inside the object. See bug 12042
2104     if (outer.isEmpty())
2105         return;
2106
2107     EBorderStyle outlineStyle = styleToUse.outlineStyle();
2108     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
2109
2110     bool useTransparencyLayer = outlineColor.hasAlpha();
2111     if (useTransparencyLayer) {
2112         if (outlineStyle == SOLID) {
2113             Path path;
2114             path.addRect(outer);
2115             path.addRect(inner);
2116             graphicsContext.setFillRule(RULE_EVENODD);
2117             graphicsContext.setFillColor(outlineColor);
2118             graphicsContext.fillPath(path);
2119             return;
2120         }
2121         graphicsContext.beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
2122         outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
2123     }
2124
2125     float leftOuter = outer.x();
2126     float leftInner = inner.x();
2127     float rightOuter = outer.maxX();
2128     float rightInner = std::min(inner.maxX(), rightOuter);
2129     float topOuter = outer.y();
2130     float topInner = inner.y();
2131     float bottomOuter = outer.maxY();
2132     float bottomInner = std::min(inner.maxY(), bottomOuter);
2133
2134     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(leftInner, bottomOuter)), BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2135     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(rightOuter, topInner)), BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2136     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(rightInner, topOuter), FloatPoint(rightOuter, bottomOuter)), BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2137     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, bottomInner), FloatPoint(rightOuter, bottomOuter)), BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2138
2139     if (useTransparencyLayer)
2140         graphicsContext.endTransparencyLayer();
2141 }
2142
2143 void RenderElement::issueRepaintForOutlineAuto(float outlineSize)
2144 {
2145     LayoutRect repaintRect;
2146     Vector<LayoutRect> focusRingRects;
2147     addFocusRingRects(focusRingRects, LayoutPoint(), containerForRepaint());
2148     for (auto rect : focusRingRects) {
2149         rect.inflate(outlineSize);
2150         repaintRect.unite(rect);
2151     }
2152     repaintRectangle(repaintRect);
2153 }
2154
2155 void RenderElement::updateOutlineAutoAncestor(bool hasOutlineAuto) const
2156 {
2157     for (auto* child = firstChild(); child; child = child->nextSibling()) {
2158         if (hasOutlineAuto == child->hasOutlineAutoAncestor())
2159             continue;
2160         child->setHasOutlineAutoAncestor(hasOutlineAuto);
2161         bool childHasOutlineAuto = child->outlineStyleForRepaint().outlineStyleIsAuto();
2162         if (childHasOutlineAuto)
2163             continue;
2164         if (!is<RenderElement>(child))
2165             continue;
2166         downcast<RenderElement>(*child).updateOutlineAutoAncestor(hasOutlineAuto);
2167     }
2168     if (hasContinuation())
2169         downcast<RenderBoxModelObject>(*this).continuation()->updateOutlineAutoAncestor(hasOutlineAuto);
2170 }
2171
2172 RenderBlock* containingBlockForFixedPosition(const RenderElement* element)
2173 {
2174     const auto* object = element;
2175     while (object && !object->canContainFixedPositionObjects())
2176         object = object->parent();
2177
2178     ASSERT(!object || !object->isAnonymousBlock());
2179     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
2180 }
2181
2182 RenderBlock* containingBlockForAbsolutePosition(const RenderElement* element)
2183 {
2184     const auto* object = element;
2185     while (object && !object->canContainAbsolutelyPositionedObjects())
2186         object = object->parent();
2187
2188     // For a relatively positioned inline, return its nearest non-anonymous containing block,
2189     // not the inline itself, to avoid having a positioned objects list in all RenderInlines
2190     // and use RenderBlock* as RenderElement::containingBlock's return type.
2191     // Use RenderBlock::container() to obtain the inline.
2192     if (object && !is<RenderBlock>(*object))
2193         object = object->containingBlock();
2194
2195     while (object && object->isAnonymousBlock())
2196         object = object->containingBlock();
2197
2198     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
2199 }
2200
2201 RenderBlock* containingBlockForObjectInFlow(const RenderElement* element)
2202 {
2203     const auto* object = element;
2204     while (object && ((object->isInline() && !object->isReplaced()) || !object->isRenderBlock()))
2205         object = object->parent();
2206     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
2207 }
2208
2209 }