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