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