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