RenderObject::flowThreadState should follow containing block instead of parent.
[WebKit-https.git] / Source / WebCore / rendering / RenderElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013, 2015 Apple Inc. All rights reserved.
7  * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "RenderElement.h"
27
28 #include "AXObjectCache.h"
29 #include "ContentData.h"
30 #include "CursorList.h"
31 #include "ElementChildIterator.h"
32 #include "EventHandler.h"
33 #include "FlowThreadController.h"
34 #include "FocusController.h"
35 #include "Frame.h"
36 #include "FrameSelection.h"
37 #include "HTMLAnchorElement.h"
38 #include "HTMLBodyElement.h"
39 #include "HTMLHtmlElement.h"
40 #include "HTMLImageElement.h"
41 #include "HTMLNames.h"
42 #include "Logging.h"
43 #include "Page.h"
44 #include "PathUtilities.h"
45 #include "RenderBlock.h"
46 #include "RenderChildIterator.h"
47 #include "RenderCounter.h"
48 #include "RenderDeprecatedFlexibleBox.h"
49 #include "RenderDescendantIterator.h"
50 #include "RenderFlexibleBox.h"
51 #include "RenderImage.h"
52 #include "RenderImageResourceStyleImage.h"
53 #include "RenderInline.h"
54 #include "RenderIterator.h"
55 #include "RenderLayer.h"
56 #include "RenderLayerCompositor.h"
57 #include "RenderLineBreak.h"
58 #include "RenderListItem.h"
59 #include "RenderNamedFlowThread.h"
60 #include "RenderRegion.h"
61 #include "RenderTableCaption.h"
62 #include "RenderTableCell.h"
63 #include "RenderTableCol.h"
64 #include "RenderTableRow.h"
65 #include "RenderText.h"
66 #include "RenderTheme.h"
67 #include "RenderView.h"
68 #include "SVGRenderSupport.h"
69 #include "Settings.h"
70 #include "ShadowRoot.h"
71 #include "StylePendingResources.h"
72 #include "StyleResolver.h"
73 #include <wtf/MathExtras.h>
74 #include <wtf/StackStats.h>
75
76 #if ENABLE(CSS_GRID_LAYOUT)
77 #include "RenderGrid.h"
78 #endif
79
80 namespace WebCore {
81
82 struct SameSizeAsRenderElement : public RenderObject {
83     uint8_t bitfields0;
84     uint8_t bitfields1;
85     uint8_t bitfields2;
86     void* firstChild;
87     void* lastChild;
88     RenderStyle style;
89 };
90
91 static_assert(sizeof(RenderElement) == sizeof(SameSizeAsRenderElement), "RenderElement should stay small");
92
93 bool RenderElement::s_affectsParentBlock = false;
94 bool RenderElement::s_noLongerAffectsParentBlock = false;
95     
96 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
97     : RenderObject(elementOrDocument)
98     , m_baseTypeFlags(baseTypeFlags)
99     , m_ancestorLineBoxDirty(false)
100     , m_hasInitializedStyle(false)
101     , m_renderInlineAlwaysCreatesLineBoxes(false)
102     , m_renderBoxNeedsLazyRepaint(false)
103     , m_hasPausedImageAnimations(false)
104     , m_hasCounterNodeMap(false)
105     , m_isCSSAnimating(false)
106     , m_hasContinuation(false)
107     , m_renderBlockHasMarginBeforeQuirk(false)
108     , m_renderBlockHasMarginAfterQuirk(false)
109     , m_renderBlockShouldForceRelayoutChildren(false)
110     , m_renderBlockFlowHasMarkupTruncation(false)
111     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
112     , m_firstChild(nullptr)
113     , m_lastChild(nullptr)
114     , m_style(WTFMove(style))
115 {
116 }
117
118 RenderElement::RenderElement(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
119     : RenderElement(static_cast<ContainerNode&>(element), WTFMove(style), baseTypeFlags)
120 {
121 }
122
123 RenderElement::RenderElement(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
124     : RenderElement(static_cast<ContainerNode&>(document), WTFMove(style), baseTypeFlags)
125 {
126 }
127
128 RenderElement::~RenderElement()
129 {
130     if (hasInitializedStyle()) {
131         for (const FillLayer* bgLayer = m_style.backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
132             if (StyleImage* backgroundImage = bgLayer->image())
133                 backgroundImage->removeClient(this);
134         }
135
136         for (const FillLayer* maskLayer = m_style.maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
137             if (StyleImage* maskImage = maskLayer->image())
138                 maskImage->removeClient(this);
139         }
140
141         if (StyleImage* borderImage = m_style.borderImage().image())
142             borderImage->removeClient(this);
143
144         if (StyleImage* maskBoxImage = m_style.maskBoxImage().image())
145             maskBoxImage->removeClient(this);
146
147         if (auto shapeValue = m_style.shapeOutside()) {
148             if (auto shapeImage = shapeValue->image())
149                 shapeImage->removeClient(this);
150         }
151     }
152     if (m_hasPausedImageAnimations)
153         view().removeRendererWithPausedImageAnimations(*this);
154     if (isRegisteredForVisibleInViewportCallback())
155         view().unregisterForVisibleInViewportCallback(*this);
156 }
157
158 RenderPtr<RenderElement> RenderElement::createFor(Element& element, RenderStyle&& style)
159 {
160     // Minimal support for content properties replacing an entire element.
161     // Works only if we have exactly one piece of content and it's a URL.
162     // Otherwise acts as if we didn't support this feature.
163     const ContentData* contentData = style.contentData();
164     if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
165         Style::loadPendingResources(style, element.document(), &element);
166         auto& styleImage = downcast<ImageContentData>(*contentData).image();
167         auto image = createRenderer<RenderImage>(element, WTFMove(style), const_cast<StyleImage*>(&styleImage));
168         image->setIsGeneratedContent();
169         return WTFMove(image);
170     }
171
172     switch (style.display()) {
173     case NONE:
174     case CONTENTS:
175         return nullptr;
176     case INLINE:
177         return createRenderer<RenderInline>(element, WTFMove(style));
178     case BLOCK:
179     case INLINE_BLOCK:
180     case COMPACT:
181         return createRenderer<RenderBlockFlow>(element, WTFMove(style));
182     case LIST_ITEM:
183         return createRenderer<RenderListItem>(element, WTFMove(style));
184     case TABLE:
185     case INLINE_TABLE:
186         return createRenderer<RenderTable>(element, WTFMove(style));
187     case TABLE_ROW_GROUP:
188     case TABLE_HEADER_GROUP:
189     case TABLE_FOOTER_GROUP:
190         return createRenderer<RenderTableSection>(element, WTFMove(style));
191     case TABLE_ROW:
192         return createRenderer<RenderTableRow>(element, WTFMove(style));
193     case TABLE_COLUMN_GROUP:
194     case TABLE_COLUMN:
195         return createRenderer<RenderTableCol>(element, WTFMove(style));
196     case TABLE_CELL:
197         return createRenderer<RenderTableCell>(element, WTFMove(style));
198     case TABLE_CAPTION:
199         return createRenderer<RenderTableCaption>(element, WTFMove(style));
200     case BOX:
201     case INLINE_BOX:
202         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTFMove(style));
203     case FLEX:
204     case INLINE_FLEX:
205     case WEBKIT_FLEX:
206     case WEBKIT_INLINE_FLEX:
207         return createRenderer<RenderFlexibleBox>(element, WTFMove(style));
208 #if ENABLE(CSS_GRID_LAYOUT)
209     case GRID:
210     case INLINE_GRID:
211         return createRenderer<RenderGrid>(element, WTFMove(style));
212 #endif
213     }
214     ASSERT_NOT_REACHED();
215     return nullptr;
216 }
217
218 std::unique_ptr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
219 {
220     if (!view().usesFirstLineRules())
221         return nullptr;
222
223     RenderElement& rendererForFirstLineStyle = isBeforeOrAfterContent() ? *parent() : const_cast<RenderElement&>(*this);
224
225     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
226         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock())
227             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == this ? style : nullptr);
228     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
229         auto& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
230         if (&parentStyle != &rendererForFirstLineStyle.parent()->style())
231             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
232     }
233     return nullptr;
234 }
235
236 const RenderStyle* RenderElement::cachedFirstLineStyle() const
237 {
238     ASSERT(view().usesFirstLineRules());
239
240     RenderElement& rendererForFirstLineStyle = isBeforeOrAfterContent() ? *parent() : const_cast<RenderElement&>(*this);
241
242     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
243         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock())
244             return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, &style());
245     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
246         auto& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
247         if (&parentStyle != &rendererForFirstLineStyle.parent()->style()) {
248             // A first-line style is in effect. Cache a first-line style for ourselves.
249             rendererForFirstLineStyle.m_style.setHasPseudoStyle(FIRST_LINE_INHERITED);
250             return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, &parentStyle);
251         }
252     }
253
254     return &style();
255 }
256
257 const RenderStyle& RenderElement::firstLineStyle() const
258 {
259     return view().usesFirstLineRules() ? *cachedFirstLineStyle() : style();
260 }
261
262 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
263 {
264     // If transform changed, and we are not composited, need to do a layout.
265     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
266         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
267         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
268             if (!hasLayer())
269                 diff = std::max(diff, StyleDifferenceLayout);
270             else {
271                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
272                 // then we actually need SimplifiedLayoutAndPositionedMovement.
273                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
274             }
275         
276         } else
277             diff = std::max(diff, StyleDifferenceRecompositeLayer);
278     }
279
280     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
281         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
282             diff = std::max(diff, StyleDifferenceRepaintLayer);
283         else
284             diff = std::max(diff, StyleDifferenceRecompositeLayer);
285     }
286
287     if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
288         if (hasLayer()
289             && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
290             && hasClipPath()
291             && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
292             diff = std::max(diff, StyleDifferenceRecompositeLayer);
293         else
294             diff = std::max(diff, StyleDifferenceRepaint);
295     }
296     
297     if (contextSensitiveProperties & ContextSensitivePropertyWillChange) {
298         if (style().willChange() && style().willChange()->canTriggerCompositing())
299             diff = std::max(diff, StyleDifferenceRecompositeLayer);
300     }
301     
302     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
303         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
304         if (!layer->isComposited() || layer->paintsWithFilters())
305             diff = std::max(diff, StyleDifferenceRepaintLayer);
306         else
307             diff = std::max(diff, StyleDifferenceRecompositeLayer);
308     }
309     
310     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
311     // style changing, since it depends on whether we decide to composite these elements. When the
312     // layer status of one of these elements changes, we need to force a layout.
313     if (diff < StyleDifferenceLayout && isRenderLayerModelObject()) {
314         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
315             diff = StyleDifferenceLayout;
316     }
317
318     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
319     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
320         diff = StyleDifferenceRepaint;
321
322     return diff;
323 }
324
325 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
326 {
327     for (auto& child : childrenOfType<RenderObject>(*this)) {
328         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
329             return true;
330         if (child.style().hasOutline() || child.style().hasBorder())
331             return true;
332     }
333     return false;
334 }
335
336 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
337 {
338     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
339 }
340
341 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
342 {
343     // Optimize the common case
344     if (FillLayer::imagesIdentical(oldLayers, newLayers))
345         return;
346     
347     // Go through the new layers and addClients first, to avoid removing all clients of an image.
348     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
349         if (currNew->image())
350             currNew->image()->addClient(this);
351     }
352
353     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
354         if (currOld->image())
355             currOld->image()->removeClient(this);
356     }
357 }
358
359 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
360 {
361     if (oldImage == newImage)
362         return;
363     if (oldImage)
364         oldImage->removeClient(this);
365     if (newImage)
366         newImage->addClient(this);
367 }
368
369 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
370 {
371     if (oldShapeValue || newShapeValue)
372         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
373 }
374
375 void RenderElement::initializeStyle()
376 {
377     Style::loadPendingResources(m_style, document(), element());
378
379     styleWillChange(StyleDifferenceNewStyle, style());
380     m_hasInitializedStyle = true;
381     styleDidChange(StyleDifferenceNewStyle, nullptr);
382
383     // We shouldn't have any text children that would need styleDidChange at this point.
384     ASSERT(!childrenOfType<RenderText>(*this).first());
385
386     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
387     // have their parent set before getting a call to initializeStyle() :|
388 }
389
390 void RenderElement::setStyle(RenderStyle&& style, StyleDifference minimalStyleDifference)
391 {
392     // FIXME: Should change RenderView so it can use initializeStyle too.
393     // If we do that, we can assert m_hasInitializedStyle unconditionally,
394     // and remove the check of m_hasInitializedStyle below too.
395     ASSERT(m_hasInitializedStyle || isRenderView());
396
397     StyleDifference diff = StyleDifferenceEqual;
398     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
399     if (m_hasInitializedStyle)
400         diff = m_style.diff(style, contextSensitiveProperties);
401
402     diff = std::max(diff, minimalStyleDifference);
403
404     diff = adjustStyleDifference(diff, contextSensitiveProperties);
405
406     Style::loadPendingResources(style, document(), element());
407
408     styleWillChange(diff, style);
409     auto oldStyle = WTFMove(m_style);
410     m_style = WTFMove(style);
411     bool detachedFromParent = !parent();
412
413     // Make sure we invalidate the containing block cache for flows when the contianing block context changes
414     // so that styleDidChange can safely use RenderBlock::locateFlowThreadContainingBlock()
415     if (oldStyle.position() != m_style.position())
416         adjustFlowThreadStateOnContainingBlockChangeIfNeeded();
417
418     styleDidChange(diff, &oldStyle);
419
420     // Text renderers use their parent style. Notify them about the change.
421     for (auto& child : childrenOfType<RenderText>(*this))
422         child.styleDidChange(diff, &oldStyle);
423
424     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
425     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
426     // we will safely bail out with the detachedFromParent flag. We might want to broaden this condition
427     // in the future as we move renderer changes out of layout and into style changes.
428     if (detachedFromParent)
429         return;
430
431     // Now that the layer (if any) has been updated, we need to adjust the diff again,
432     // check whether we should layout now, and decide if we need to repaint.
433     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
434     
435     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
436         if (updatedDiff == StyleDifferenceLayout)
437             setNeedsLayoutAndPrefWidthsRecalc();
438         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
439             setNeedsPositionedMovementLayout(&oldStyle);
440         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
441             setNeedsPositionedMovementLayout(&oldStyle);
442             setNeedsSimplifiedNormalFlowLayout();
443         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
444             setNeedsSimplifiedNormalFlowLayout();
445     }
446
447     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
448         // Do a repaint with the new style now, e.g., for example if we go from
449         // not having an outline to having an outline.
450         repaint();
451     }
452 }
453
454 bool RenderElement::childRequiresTable(const RenderObject& child) const
455 {
456     if (is<RenderTableCol>(child)) {
457         const RenderTableCol& newTableColumn = downcast<RenderTableCol>(child);
458         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
459         return !is<RenderTable>(*this) && !isColumnInColumnGroup;
460     }
461     if (is<RenderTableCaption>(child))
462         return !is<RenderTable>(*this);
463
464     if (is<RenderTableSection>(child))
465         return !is<RenderTable>(*this);
466
467     if (is<RenderTableRow>(child))
468         return !is<RenderTableSection>(*this);
469
470     if (is<RenderTableCell>(child))
471         return !is<RenderTableRow>(*this);
472
473     return false;
474 }
475
476 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
477 {
478     if (childRequiresTable(*newChild)) {
479         RenderTable* table;
480         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
481         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
482             table = downcast<RenderTable>(afterChild);
483         else {
484             table = RenderTable::createAnonymousWithParentRenderer(*this).release();
485             addChild(table, beforeChild);
486         }
487         table->addChild(newChild);
488     } else
489         insertChildInternal(newChild, beforeChild, NotifyChildren);
490
491     if (is<RenderText>(*newChild))
492         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
493
494     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
495     // <g>s to have renderers - at least that's how our implementation works. Consider:
496     // <g display="none"><foreignObject><body style="position: relative">FOO...
497     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
498     // - when the document is painted, both layers are painted. The <body> layer doesn't
499     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
500     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
501     // and stop creating layers at all for these cases - they're not used anyways.
502     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
503         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
504
505     SVGRenderSupport::childAdded(*this, *newChild);
506 }
507
508 void RenderElement::removeChild(RenderObject& oldChild)
509 {
510     removeChildInternal(oldChild, NotifyChildren);
511 }
512
513 void RenderElement::destroyLeftoverChildren()
514 {
515     while (m_firstChild) {
516         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
517             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
518         } else {
519             // 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.
520             if (m_firstChild->node())
521                 m_firstChild->node()->setRenderer(nullptr);
522             m_firstChild->destroy();
523         }
524     }
525 }
526
527 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
528 {
529     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
530     ASSERT(!newChild->parent());
531     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
532
533     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
534         beforeChild = beforeChild->parent();
535
536     // This should never happen, but if it does prevent render tree corruption
537     // where child->parent() ends up being owner but child->nextSibling()->parent()
538     // is not owner.
539     if (beforeChild && beforeChild->parent() != this) {
540         ASSERT_NOT_REACHED();
541         return;
542     }
543
544     newChild->setParent(this);
545
546     if (m_firstChild == beforeChild)
547         m_firstChild = newChild;
548
549     if (beforeChild) {
550         RenderObject* previousSibling = beforeChild->previousSibling();
551         if (previousSibling)
552             previousSibling->setNextSibling(newChild);
553         newChild->setPreviousSibling(previousSibling);
554         newChild->setNextSibling(beforeChild);
555         beforeChild->setPreviousSibling(newChild);
556     } else {
557         if (lastChild())
558             lastChild()->setNextSibling(newChild);
559         newChild->setPreviousSibling(lastChild());
560         m_lastChild = newChild;
561     }
562
563     newChild->initializeFlowThreadStateOnInsertion();
564     if (!documentBeingDestroyed()) {
565         if (notifyChildren == NotifyChildren)
566             newChild->insertedIntoTree();
567         if (is<RenderElement>(*newChild))
568             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
569     }
570
571     newChild->setNeedsLayoutAndPrefWidthsRecalc();
572     setPreferredLogicalWidthsDirty(true);
573     if (!normalChildNeedsLayout())
574         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
575
576     if (AXObjectCache* cache = document().axObjectCache())
577         cache->childrenChanged(this, newChild);
578     if (is<RenderBlockFlow>(*this))
579         downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
580     if (hasOutlineAutoAncestor() || outlineStyleForRepaint().outlineStyleIsAuto())
581         newChild->setHasOutlineAutoAncestor();
582 }
583
584 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
585 {
586     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
587     ASSERT(oldChild.parent() == this);
588
589     if (oldChild.isFloatingOrOutOfFlowPositioned())
590         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
591
592     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
593     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
594     // disappears gets repainted properly.
595     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
596         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
597         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
598         if (oldChild.isBody())
599             view().repaintRootContents();
600         else
601             oldChild.repaint();
602     }
603
604     // If we have a line box wrapper, delete it.
605     if (is<RenderBox>(oldChild))
606         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
607     else if (is<RenderLineBreak>(oldChild))
608         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
609
610     // If oldChild is the start or end of the selection, then clear the selection to
611     // avoid problems of invalid pointers.
612     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
613         frame().selection().setNeedsSelectionUpdate();
614
615     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
616         oldChild.willBeRemovedFromTree();
617
618     oldChild.resetFlowThreadStateOnRemoval();
619
620     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
621     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
622     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
623     
624     RenderObject* nextSibling = oldChild.nextSibling();
625
626     if (oldChild.previousSibling())
627         oldChild.previousSibling()->setNextSibling(nextSibling);
628     if (nextSibling)
629         nextSibling->setPreviousSibling(oldChild.previousSibling());
630
631     if (m_firstChild == &oldChild)
632         m_firstChild = nextSibling;
633     if (m_lastChild == &oldChild)
634         m_lastChild = oldChild.previousSibling();
635
636     oldChild.setPreviousSibling(nullptr);
637     oldChild.setNextSibling(nullptr);
638     oldChild.setParent(nullptr);
639
640     // rendererRemovedFromTree walks the whole subtree. We can improve performance
641     // by skipping this step when destroying the entire tree.
642     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
643         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
644
645     if (AXObjectCache* cache = document().existingAXObjectCache())
646         cache->childrenChanged(this);
647 }
648
649 RenderBlock* RenderElement::containingBlockForFixedPosition() const
650 {
651     auto* renderer = parent();
652     while (renderer && !renderer->canContainFixedPositionObjects())
653         renderer = renderer->parent();
654
655     ASSERT(!renderer || !renderer->isAnonymousBlock());
656     return downcast<RenderBlock>(renderer);
657 }
658
659 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
660 {
661     // A relatively positioned RenderInline forwards its absolute positioned descendants to
662     // its nearest non-anonymous containing block (to avoid having a positioned objects list in all RenderInlines).
663     auto* renderer = isRenderInline() ? const_cast<RenderElement*>(downcast<RenderElement>(this)) : parent();
664     while (renderer && !renderer->canContainAbsolutelyPositionedObjects())
665         renderer = renderer->parent();
666     // Make sure we only return non-anonymous RenderBlock as containing block.
667     while (renderer && (!is<RenderBlock>(*renderer) || renderer->isAnonymousBlock()))
668         renderer = renderer->containingBlock();
669     return downcast<RenderBlock>(renderer);
670 }
671
672 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
673 {
674     if (renderer.hasLayer()) {
675         if (!beforeChild && newObject) {
676             // We need to figure out the layer that follows newObject. We only do
677             // this the first time we find a child layer, and then we update the
678             // pointer values for newObject and beforeChild used by everyone else.
679             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
680             newObject = nullptr;
681         }
682         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
683         return;
684     }
685
686     for (auto& child : childrenOfType<RenderElement>(renderer))
687         addLayers(child, parentLayer, newObject, beforeChild);
688 }
689
690 void RenderElement::addLayers(RenderLayer* parentLayer)
691 {
692     if (!parentLayer)
693         return;
694
695     RenderElement* renderer = this;
696     RenderLayer* beforeChild = nullptr;
697     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
698 }
699
700 void RenderElement::removeLayers(RenderLayer* parentLayer)
701 {
702     if (!parentLayer)
703         return;
704
705     if (hasLayer()) {
706         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
707         return;
708     }
709
710     for (auto& child : childrenOfType<RenderElement>(*this))
711         child.removeLayers(parentLayer);
712 }
713
714 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
715 {
716     if (!newParent)
717         return;
718
719     if (hasLayer()) {
720         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
721         ASSERT(oldParent == layer->parent());
722         if (oldParent)
723             oldParent->removeChild(layer);
724         newParent->addChild(layer);
725         return;
726     }
727
728     for (auto& child : childrenOfType<RenderElement>(*this))
729         child.moveLayers(oldParent, newParent);
730 }
731
732 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
733 {
734     // Error check the parent layer passed in. If it's null, we can't find anything.
735     if (!parentLayer)
736         return nullptr;
737
738     // Step 1: If our layer is a child of the desired parent, then return our layer.
739     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
740     if (ourLayer && ourLayer->parent() == parentLayer)
741         return ourLayer;
742
743     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
744     // into our siblings trying to find the next layer whose parent is the desired parent.
745     if (!ourLayer || ourLayer == parentLayer) {
746         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
747             if (!is<RenderElement>(*child))
748                 continue;
749             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
750             if (nextLayer)
751                 return nextLayer;
752         }
753     }
754
755     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
756     // find anything.
757     if (parentLayer == ourLayer)
758         return nullptr;
759
760     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
761     // follow us to see if we can locate a layer.
762     if (checkParent && parent())
763         return parent()->findNextLayer(parentLayer, this, true);
764
765     return nullptr;
766 }
767
768 bool RenderElement::layerCreationAllowedForSubtree() const
769 {
770     RenderElement* parentRenderer = parent();
771     while (parentRenderer) {
772         if (parentRenderer->isSVGHiddenContainer())
773             return false;
774         parentRenderer = parentRenderer->parent();
775     }
776     
777     return true;
778 }
779
780 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
781 {
782     // FIXME: We could save this call when the change only affected non-inherited properties.
783     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
784         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
785             continue;
786
787         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
788             continue;
789
790 #if ENABLE(FULLSCREEN_API)
791         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
792             continue;
793 #endif
794
795         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
796         if (is<RenderFlowThread>(elementChild))
797             continue;
798
799         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), elementChild.style().display());
800         if (style().specifiesColumns()) {
801             if (elementChild.style().specifiesColumns())
802                 newStyle.inheritColumnPropertiesFrom(&style());
803             if (elementChild.style().columnSpan())
804                 newStyle.setColumnSpan(ColumnSpanAll);
805         }
806
807         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
808         // they contain block descendants of relative or sticky positioned inlines.
809         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
810             newStyle.setPosition(elementChild.style().position());
811
812         elementChild.setStyle(WTFMove(newStyle));
813     }
814 }
815
816 static inline bool rendererHasBackground(const RenderElement* renderer)
817 {
818     return renderer && renderer->hasBackground();
819 }
820
821 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
822 {
823     auto* oldStyle = hasInitializedStyle() ? &style() : nullptr;
824     if (oldStyle) {
825         // If our z-index changes value or our visibility changes,
826         // we need to dirty our stacking context's z-order list.
827         bool visibilityChanged = m_style.visibility() != newStyle.visibility()
828             || m_style.zIndex() != newStyle.zIndex()
829             || m_style.hasAutoZIndex() != newStyle.hasAutoZIndex();
830 #if ENABLE(DASHBOARD_SUPPORT)
831         if (visibilityChanged)
832             document().setAnnotatedRegionsDirty(true);
833 #endif
834 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
835         if (visibilityChanged)
836             document().dirtyTouchEventRects();
837 #endif
838         if (visibilityChanged) {
839             if (AXObjectCache* cache = document().existingAXObjectCache())
840                 cache->childrenChanged(parent(), this);
841         }
842
843         // Keep layer hierarchy visibility bits up to date if visibility changes.
844         if (m_style.visibility() != newStyle.visibility()) {
845             if (RenderLayer* layer = enclosingLayer()) {
846                 if (newStyle.visibility() == VISIBLE)
847                     layer->setHasVisibleContent();
848                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
849                     layer->dirtyVisibleContentStatus();
850                     if (diff > StyleDifferenceRepaintLayer)
851                         repaint();
852                 }
853             }
854         }
855
856         if (m_parent && (newStyle.outlineSize() < m_style.outlineSize() || shouldRepaintForStyleDifference(diff)))
857             repaint();
858         if (isFloating() && m_style.floating() != newStyle.floating()) {
859             // For changes in float styles, we need to conceivably remove ourselves
860             // from the floating objects list.
861             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
862         } else if (isOutOfFlowPositioned() && m_style.position() != newStyle.position()) {
863             // For changes in positioning styles, we need to conceivably remove ourselves
864             // from the positioned objects list.
865             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
866         }
867
868         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
869             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
870             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
871
872         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
873             && parent() && parent()->isRenderBlock();
874
875         // reset style flags
876         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
877             setFloating(false);
878             clearPositionedState();
879         }
880         setHorizontalWritingMode(true);
881         setHasVisibleBoxDecorations(false);
882         setHasOverflowClip(false);
883         setHasTransformRelatedProperty(false);
884         setHasReflection(false);
885     } else {
886         s_affectsParentBlock = false;
887         s_noLongerAffectsParentBlock = false;
888     }
889
890     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
891     bool oldStyleUsesFixedBackgrounds = m_style.hasFixedBackgroundImage();
892     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
893         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
894
895         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
896         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
897         bool drawsRootBackground = isDocumentElementRenderer() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
898         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
899             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
900                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
901                     newStyleSlowScroll = false;
902
903                 if (oldStyleSlowScroll && m_style.hasEntirelyFixedBackground())
904                     oldStyleSlowScroll = false;
905             }
906         }
907
908         if (oldStyleSlowScroll != newStyleSlowScroll) {
909             if (oldStyleSlowScroll)
910                 view().frameView().removeSlowRepaintObject(this);
911
912             if (newStyleSlowScroll)
913                 view().frameView().addSlowRepaintObject(this);
914         }
915     }
916
917     if (isDocumentElementRenderer() || isBody())
918         view().frameView().updateExtendBackgroundIfNecessary();
919 }
920
921 void RenderElement::handleDynamicFloatPositionChange()
922 {
923     // We have gone from not affecting the inline status of the parent flow to suddenly
924     // having an impact.  See if there is a mismatch between the parent flow's
925     // childrenInline() state and our state.
926     setInline(style().isDisplayInlineType());
927     if (isInline() != parent()->childrenInline()) {
928         if (!isInline())
929             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
930         else {
931             // An anonymous block must be made to wrap this inline.
932             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
933             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
934             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
935             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
936         }
937     }
938 }
939
940 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
941 {
942     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
943     if (!parentBlock.canDropAnonymousBlockChild())
944         return;
945
946     // We have changed to floated or out-of-flow positioning so maybe all our parent's
947     // children can be inline now. Bail if there are any block children left on the line,
948     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
949     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
950     // if we find a continuation.
951     RenderObject* current = parent()->firstChild();
952     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
953         current = current->nextSibling();
954
955     if (current)
956         return;
957
958     RenderObject* next;
959     for (current = parent()->firstChild(); current; current = next) {
960         next = current->nextSibling();
961         if (current->isAnonymousBlock())
962             parentBlock.dropAnonymousBoxChild(parentBlock, downcast<RenderBlock>(*current));
963     }
964 }
965
966 #if !PLATFORM(IOS)
967 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
968 {
969     ASSERT(a->cursors() != b->cursors());
970     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
971 }
972
973 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
974 {
975     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
976 }
977 #endif
978
979 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
980 {
981     updateFillImages(oldStyle ? oldStyle->backgroundLayers() : nullptr, m_style.backgroundLayers());
982     updateFillImages(oldStyle ? oldStyle->maskLayers() : nullptr, m_style.maskLayers());
983     updateImage(oldStyle ? oldStyle->borderImage().image() : nullptr, m_style.borderImage().image());
984     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : nullptr, m_style.maskBoxImage().image());
985     updateShapeImage(oldStyle ? oldStyle->shapeOutside() : nullptr, m_style.shapeOutside());
986
987     if (s_affectsParentBlock)
988         handleDynamicFloatPositionChange();
989
990     if (s_noLongerAffectsParentBlock) {
991         removeAnonymousWrappersForInlinesIfNecessary();
992         // Fresh floats need to be reparented if they actually belong to the previous anonymous block.
993         // It copies the logic of RenderBlock::addChildIgnoringContinuation
994         if (style().isFloating() && previousSibling() && previousSibling()->isAnonymousBlock())
995             downcast<RenderBoxModelObject>(*parent()).moveChildTo(&downcast<RenderBoxModelObject>(*previousSibling()), this);
996     }
997
998     SVGRenderSupport::styleChanged(*this, oldStyle);
999
1000     if (!m_parent)
1001         return;
1002     
1003     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1004         RenderCounter::rendererStyleChanged(*this, oldStyle, &m_style);
1005
1006         // If the object already needs layout, then setNeedsLayout won't do
1007         // any work. But if the containing block has changed, then we may need
1008         // to mark the new containing blocks for layout. The change that can
1009         // directly affect the containing block of this object is a change to
1010         // the position style.
1011         if (needsLayout() && oldStyle->position() != m_style.position())
1012             markContainingBlocksForLayout();
1013
1014         if (diff == StyleDifferenceLayout)
1015             setNeedsLayoutAndPrefWidthsRecalc();
1016         else
1017             setNeedsSimplifiedNormalFlowLayout();
1018     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1019         setNeedsPositionedMovementLayout(oldStyle);
1020         setNeedsSimplifiedNormalFlowLayout();
1021     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1022         setNeedsPositionedMovementLayout(oldStyle);
1023
1024     // Don't check for repaint here; we need to wait until the layer has been
1025     // updated by subclasses before we know if we have to repaint (in setStyle()).
1026
1027 #if !PLATFORM(IOS)
1028     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1029         frame().eventHandler().scheduleCursorUpdate();
1030 #endif
1031     bool hadOutlineAuto = oldStyle && oldStyle->outlineStyleIsAuto();
1032     bool hasOutlineAuto = outlineStyleForRepaint().outlineStyleIsAuto();
1033     if (hasOutlineAuto != hadOutlineAuto) {
1034         updateOutlineAutoAncestor(hasOutlineAuto);
1035         issueRepaintForOutlineAuto(hasOutlineAuto ? outlineStyleForRepaint().outlineSize() : oldStyle->outlineSize());
1036     }
1037 }
1038
1039 void RenderElement::insertedIntoTree()
1040 {
1041     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1042     // and don't have a layer attached to ourselves.
1043     RenderLayer* layer = nullptr;
1044     if (firstChild() || hasLayer()) {
1045         layer = parent()->enclosingLayer();
1046         addLayers(layer);
1047     }
1048
1049     // If |this| is visible but this object was not, tell the layer it has some visible content
1050     // that needs to be drawn and layer visibility optimization can't be used
1051     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1052         if (!layer)
1053             layer = parent()->enclosingLayer();
1054         if (layer)
1055             layer->setHasVisibleContent();
1056     }
1057
1058     RenderObject::insertedIntoTree();
1059 }
1060
1061 void RenderElement::willBeRemovedFromTree()
1062 {
1063     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1064     RenderLayer* layer = nullptr;
1065     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1066         if ((layer = parent()->enclosingLayer()))
1067             layer->dirtyVisibleContentStatus();
1068     }
1069     // Keep our layer hierarchy updated.
1070     if (firstChild() || hasLayer()) {
1071         if (!layer)
1072             layer = parent()->enclosingLayer();
1073         removeLayers(layer);
1074     }
1075
1076     if (m_style.hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1077         view().frameView().removeSlowRepaintObject(this);
1078
1079     if (isOutOfFlowPositioned() && parent()->childrenInline())
1080         parent()->dirtyLinesFromChangedChild(*this);
1081
1082     RenderObject::willBeRemovedFromTree();
1083 }
1084
1085 inline void RenderElement::clearLayoutRootIfNeeded() const
1086 {
1087     if (documentBeingDestroyed())
1088         return;
1089
1090     if (view().frameView().layoutRoot() != this)
1091         return;
1092
1093     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
1094     // which ensures that this renderer is no longer the layout root.
1095     ASSERT_NOT_REACHED();
1096     
1097     // This indicates a failure to layout the child, which is why
1098     // the layout root is still set to |this|. Make sure to clear it
1099     // since we are getting destroyed.
1100     view().frameView().clearLayoutRoot();
1101 }
1102
1103 void RenderElement::willBeDestroyed()
1104 {
1105     animation().cancelAnimations(*this);
1106
1107     destroyLeftoverChildren();
1108
1109     if (hasCounterNodeMap())
1110         RenderCounter::destroyCounterNodes(*this);
1111
1112     RenderObject::willBeDestroyed();
1113
1114 #if !ASSERT_DISABLED
1115     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1116         // After remove, the object and the associated information should not be in any flow thread.
1117         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1118             ASSERT(!flowThread->hasChildInfo(this));
1119         }
1120     }
1121 #endif
1122     clearLayoutRootIfNeeded();
1123 }
1124
1125 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1126 {
1127     ASSERT(!isSetNeedsLayoutForbidden());
1128     if (needsPositionedMovementLayout())
1129         return;
1130     setNeedsPositionedMovementLayoutBit(true);
1131     markContainingBlocksForLayout();
1132     if (hasLayer()) {
1133         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1134             setLayerNeedsFullRepaint();
1135         else
1136             setLayerNeedsFullRepaintForPositionedMovementLayout();
1137     }
1138 }
1139
1140 void RenderElement::clearChildNeedsLayout()
1141 {
1142     setNormalChildNeedsLayoutBit(false);
1143     setPosChildNeedsLayoutBit(false);
1144     setNeedsSimplifiedNormalFlowLayoutBit(false);
1145     setNormalChildNeedsLayoutBit(false);
1146     setNeedsPositionedMovementLayoutBit(false);
1147 }
1148
1149 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1150 {
1151     ASSERT(!isSetNeedsLayoutForbidden());
1152     if (needsSimplifiedNormalFlowLayout())
1153         return;
1154     setNeedsSimplifiedNormalFlowLayoutBit(true);
1155     markContainingBlocksForLayout();
1156     if (hasLayer())
1157         setLayerNeedsFullRepaint();
1158 }
1159
1160 RenderElement& RenderElement::rendererForRootBackground()
1161 {
1162     ASSERT(isDocumentElementRenderer());
1163     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1164         // Locate the <body> element using the DOM. This is easier than trying
1165         // to crawl around a render tree with potential :before/:after content and
1166         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1167         // render object very easily via the DOM.
1168         if (auto* body = document().body()) {
1169             if (auto* renderer = body->renderer())
1170                 return *renderer;
1171         }
1172     }
1173     return *this;
1174 }
1175
1176 RenderElement* RenderElement::hoverAncestor() const
1177 {
1178     // When searching for the hover ancestor and encountering a named flow thread,
1179     // the search will continue with the DOM ancestor of the top-most element
1180     // in the named flow thread.
1181     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1182     RenderElement* hoverAncestor = parent();
1183
1184     // Skip anonymous blocks directly flowed into flow threads as it would
1185     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1186     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1187         hoverAncestor = hoverAncestor->parent();
1188
1189     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1190         hoverAncestor = nullptr;
1191         if (Element* element = this->element()) {
1192             if (auto parent = element->parentNode())
1193                 hoverAncestor = parent->renderer();
1194         }
1195     }
1196
1197     return hoverAncestor;
1198 }
1199
1200 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1201 {
1202     paintInfo.phase = phase;
1203     element.paint(paintInfo, childPoint);
1204 }
1205
1206 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1207 {
1208     // Paint all phases atomically, as though the element established its own stacking context.
1209     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1210     // This is also used by other elements (e.g. flex items and grid items).
1211     if (paintInfo.phase == PaintPhaseSelection) {
1212         paint(paintInfo, childPoint);
1213     } else if (paintInfo.phase == PaintPhaseForeground) {
1214         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1215         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1216         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1217         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1218         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1219
1220         // Reset |paintInfo| to the original phase.
1221         paintInfo.phase = PaintPhaseForeground;
1222     }
1223 }
1224
1225 void RenderElement::layout()
1226 {
1227     StackStats::LayoutCheckPoint layoutCheckPoint;
1228     ASSERT(needsLayout());
1229     RenderObject* child = firstChild();
1230     while (child) {
1231         if (child->needsLayout())
1232             downcast<RenderElement>(*child).layout();
1233         ASSERT(!child->needsLayout());
1234         child = child->nextSibling();
1235     }
1236     clearNeedsLayout();
1237 }
1238
1239 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1240 {
1241     // Nobody will use multiple layers without wanting fancy positioning.
1242     if (layer->next())
1243         return true;
1244
1245     // Make sure we have a valid image.
1246     StyleImage* image = layer->image();
1247     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1248         return false;
1249
1250     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1251         return true;
1252
1253     EFillSizeType sizeType = layer->sizeType();
1254
1255     if (sizeType == Contain || sizeType == Cover)
1256         return true;
1257
1258     if (sizeType == SizeLength) {
1259         LengthSize size = layer->sizeLength();
1260         if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1261             return true;
1262         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1263         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1264             return true;
1265     } else if (image->usesImageContainerSize())
1266         return true;
1267
1268     return false;
1269 }
1270
1271 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1272 {
1273     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1274         return true;
1275
1276     // If we don't have a background/border/mask, then nothing to do.
1277     if (!renderer.hasVisibleBoxDecorations())
1278         return false;
1279
1280     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1281         return true;
1282
1283     // Our fill layers are ok. Let's check border.
1284     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1285         return true;
1286
1287     return false;
1288 }
1289
1290 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1291 {
1292     if (view().printing())
1293         return false; // Don't repaint if we're printing.
1294
1295     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1296     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1297     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1298     LayoutRect newOutlineBox;
1299
1300     bool fullRepaint = selfNeedsLayout();
1301     // Presumably a background or a border exists if border-fit:lines was specified.
1302     if (!fullRepaint && style().borderFit() == BorderFitLines)
1303         fullRepaint = true;
1304     if (!fullRepaint) {
1305         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1306         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1307         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1308         fullRepaint = (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)));
1309     }
1310
1311     if (!repaintContainer)
1312         repaintContainer = &view();
1313
1314     if (fullRepaint) {
1315         repaintUsingContainer(repaintContainer, oldBounds);
1316         if (newBounds != oldBounds)
1317             repaintUsingContainer(repaintContainer, newBounds);
1318         return true;
1319     }
1320
1321     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1322         return false;
1323
1324     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1325     if (deltaLeft > 0)
1326         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1327     else if (deltaLeft < 0)
1328         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1329
1330     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1331     if (deltaRight > 0)
1332         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1333     else if (deltaRight < 0)
1334         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1335
1336     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1337     if (deltaTop > 0)
1338         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1339     else if (deltaTop < 0)
1340         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1341
1342     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1343     if (deltaBottom > 0)
1344         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1345     else if (deltaBottom < 0)
1346         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1347
1348     if (newOutlineBox == oldOutlineBox)
1349         return false;
1350
1351     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1352     // two rectangles (but typically only one).
1353     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1354     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1355     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1356     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1357     if (width) {
1358         LayoutUnit shadowLeft;
1359         LayoutUnit shadowRight;
1360         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1361         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1362         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1363         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1364         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1365         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1366         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1367             newOutlineBox.y(),
1368             width + decorationsWidth,
1369             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1370         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1371         if (rightRect.x() < right) {
1372             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1373             repaintUsingContainer(repaintContainer, rightRect);
1374         }
1375     }
1376     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1377     if (height) {
1378         LayoutUnit shadowTop;
1379         LayoutUnit shadowBottom;
1380         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1381         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1382         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1383         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1384         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1385             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1386         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1387         LayoutRect bottomRect(newOutlineBox.x(),
1388             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1389             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1390             height + decorationsHeight);
1391         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1392         if (bottomRect.y() < bottom) {
1393             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1394             repaintUsingContainer(repaintContainer, bottomRect);
1395         }
1396     }
1397     return false;
1398 }
1399
1400 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1401 {
1402     ASSERT(style().hasBorder());
1403
1404     StyleImage* borderImage = style().borderImage().image();
1405     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1406 }
1407
1408 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1409 {
1410     auto& frameView = view().frameView();
1411     if (frameView.isOffscreen())
1412         return false;
1413
1414     if (!hasOverflowClip()) {
1415         // FIXME: Computing the overflow rect is expensive if any descendant has
1416         // its own self-painting layer. As a result, we prefer to abort early in
1417         // this case and assume it may cause us to repaint inside the viewport.
1418         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1419             return true;
1420     }
1421
1422     // Compute viewport rect if it was not provided.
1423     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1424     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1425 }
1426
1427 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1428 {
1429     const Document& document = renderer.document();
1430     if (document.pageCacheState() != Document::NotInPageCache)
1431         return false;
1432     if (document.activeDOMObjectsAreSuspended())
1433         return false;
1434     if (renderer.style().visibility() != VISIBLE)
1435         return false;
1436     if (renderer.view().frameView().isOffscreen())
1437         return false;
1438
1439     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1440     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1441     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1442     // can no longer check if it is a background image.
1443     bool backgroundIsPaintedByRoot = renderer.isDocumentElementRenderer();
1444     if (renderer.isBody()) {
1445         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1446         ASSERT(rootRenderer.isDocumentElementRenderer());
1447         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1448         // FIXME: Should share body background propagation code.
1449         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1450
1451     }
1452     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect() : renderer.absoluteClippedOverflowRect();
1453     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1454         return false;
1455
1456     return true;
1457 }
1458
1459 void RenderElement::registerForVisibleInViewportCallback()
1460 {
1461     if (isRegisteredForVisibleInViewportCallback())
1462         return;
1463     setIsRegisteredForVisibleInViewportCallback(true);
1464
1465     view().registerForVisibleInViewportCallback(*this);
1466 }
1467
1468 void RenderElement::unregisterForVisibleInViewportCallback()
1469 {
1470     if (!isRegisteredForVisibleInViewportCallback())
1471         return;
1472     setIsRegisteredForVisibleInViewportCallback(false);
1473
1474     view().unregisterForVisibleInViewportCallback(*this);
1475 }
1476
1477 void RenderElement::visibleInViewportStateChanged(VisibleInViewportState state)
1478 {
1479     if (state == visibleInViewportState())
1480         return;
1481     setVisibleInViewportState(state);
1482
1483     if (element())
1484         element()->isVisibleInViewportChanged();
1485 }
1486
1487 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1488 {
1489     if (document().pageCacheState() != Document::NotInPageCache)
1490         return;
1491     auto& frameView = view().frameView();
1492     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1493     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1494         // FIXME: It would be better to pass the image along with the renderer
1495         // so that we can be smarter about detecting if the image is inside the
1496         // viewport in repaintForPausedImageAnimationsIfNeeded().
1497         view().addRendererWithPausedImageAnimations(*this);
1498         return;
1499     }
1500     imageChanged(&image);
1501 }
1502
1503 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1504 {
1505     ASSERT(m_hasPausedImageAnimations);
1506     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1507         return false;
1508
1509     repaint();
1510
1511     // For directly-composited animated GIFs it does not suffice to call repaint() to resume animation. We need to mark the image as changed.
1512     if (is<RenderBoxModelObject>(*this))
1513         downcast<RenderBoxModelObject>(*this).contentChanged(ImageChanged);
1514
1515     return true;
1516 }
1517
1518 const RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, const RenderStyle* parentStyle) const
1519 {
1520     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1521         return nullptr;
1522
1523     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1524     if (cachedStyle)
1525         return cachedStyle;
1526
1527     std::unique_ptr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1528     if (result)
1529         return const_cast<RenderStyle&>(m_style).addCachedPseudoStyle(WTFMove(result));
1530     return nullptr;
1531 }
1532
1533 RenderStyle* RenderElement::getMutableCachedPseudoStyle(PseudoId pseudo, const RenderStyle* parentStyle)
1534 {
1535     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1536         return nullptr;
1537
1538     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1539     if (cachedStyle)
1540         return cachedStyle;
1541
1542     std::unique_ptr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1543     if (result)
1544         return m_style.addCachedPseudoStyle(WTFMove(result));
1545     return nullptr;
1546 }
1547
1548 std::unique_ptr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, const RenderStyle* parentStyle, const RenderStyle* ownStyle) const
1549 {
1550     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1551         return nullptr;
1552
1553     if (!parentStyle) {
1554         ASSERT(!ownStyle);
1555         parentStyle = &style();
1556     }
1557
1558     if (isAnonymous())
1559         return nullptr;
1560
1561     auto& styleResolver = element()->styleResolver();
1562
1563     std::unique_ptr<RenderStyle> style;
1564     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1565         style = styleResolver.styleForElement(*element(), parentStyle).renderStyle;
1566         style->setStyleType(FIRST_LINE_INHERITED);
1567     } else
1568         style = styleResolver.pseudoStyleForElement(*element(), pseudoStyleRequest, *parentStyle);
1569
1570     if (style)
1571         Style::loadPendingResources(*style, document(), element());
1572
1573     return style;
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->mode() == ShadowRootMode::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     auto& 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.isOpaque();
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(outlineColor.alphaAsFloat());
2109         outlineColor = outlineColor.opaqueColor();
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)
2143 {
2144     for (auto& child : childrenOfType<RenderObject>(*this)) {
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 bool RenderElement::hasOutlineAnnotation() const
2160 {
2161     return element() && element()->isLink() && document().printing();
2162 }
2163
2164 bool RenderElement::hasSelfPaintingLayer() const
2165 {
2166     if (!hasLayer())
2167         return false;
2168     auto& layerModelObject = downcast<RenderLayerModelObject>(*this);
2169     return layerModelObject.hasSelfPaintingLayer();
2170 }
2171
2172 bool RenderElement::checkForRepaintDuringLayout() const
2173 {
2174     return !document().view()->needsFullRepaint() && everHadLayout() && !hasSelfPaintingLayer();
2175 }
2176
2177 RespectImageOrientationEnum RenderElement::shouldRespectImageOrientation() const
2178 {
2179 #if USE(CG) || USE(CAIRO)
2180     // This can only be enabled for ports which honor the orientation flag in their drawing code.
2181     if (document().isImageDocument())
2182         return RespectImageOrientation;
2183 #endif
2184     // Respect the image's orientation if it's being used as a full-page image or it's
2185     // an <img> and the setting to respect it everywhere is set.
2186     return (frame().settings().shouldRespectImageOrientation() && is<HTMLImageElement>(element())) ? RespectImageOrientation : DoNotRespectImageOrientation;
2187 }
2188
2189 void RenderElement::adjustFlowThreadStateOnContainingBlockChangeIfNeeded()
2190 {
2191     if (flowThreadState() == NotInsideFlowThread)
2192         return;
2193
2194     // Invalidate the containing block caches.
2195     if (is<RenderBlock>(*this))
2196         downcast<RenderBlock>(*this).resetFlowThreadContainingBlockAndChildInfoIncludingDescendants();
2197     
2198     // Adjust the flow tread state on the subtree.
2199     setFlowThreadState(RenderObject::computedFlowThreadState(*this));
2200     for (auto& descendant : descendantsOfType<RenderObject>(*this))
2201         descendant.setFlowThreadState(RenderObject::computedFlowThreadState(descendant));
2202 }
2203
2204 void RenderElement::removeFromRenderFlowThread()
2205 {
2206     ASSERT(flowThreadState() != NotInsideFlowThread);
2207     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2208     // It's only until later when we actually destroy it and remove all the children from it.
2209     // Currently, that happens for firstLetter elements and list markers.
2210     // Pass in the flow thread so that we don't have to look it up for all the children.
2211     removeFromRenderFlowThreadIncludingDescendants(true);
2212 }
2213
2214 void RenderElement::removeFromRenderFlowThreadIncludingDescendants(bool shouldUpdateState)
2215 {
2216     // Once we reach another flow thread we don't need to update the flow thread state
2217     // but we have to continue cleanup the flow thread info.
2218     if (isRenderFlowThread())
2219         shouldUpdateState = false;
2220
2221     for (auto& child : childrenOfType<RenderObject>(*this)) {
2222         if (is<RenderElement>(child)) {
2223             downcast<RenderElement>(child).removeFromRenderFlowThreadIncludingDescendants(shouldUpdateState);
2224             continue;
2225         }
2226         if (shouldUpdateState)
2227             child.setFlowThreadState(NotInsideFlowThread);
2228     }
2229
2230     // We have to ask for our containing flow thread as it may be above the removed sub-tree.
2231     RenderFlowThread* flowThreadContainingBlock = this->flowThreadContainingBlock();
2232     while (flowThreadContainingBlock) {
2233         flowThreadContainingBlock->removeFlowChildInfo(*this);
2234
2235         if (flowThreadContainingBlock->flowThreadState() == NotInsideFlowThread)
2236             break;
2237         auto* parent = flowThreadContainingBlock->parent();
2238         if (!parent)
2239             break;
2240         flowThreadContainingBlock = parent->flowThreadContainingBlock();
2241     }
2242     if (is<RenderBlock>(*this))
2243         downcast<RenderBlock>(*this).setCachedFlowThreadContainingBlockNeedsUpdate();
2244
2245     if (shouldUpdateState)
2246         setFlowThreadState(NotInsideFlowThread);
2247 }
2248
2249 #if ENABLE(TEXT_AUTOSIZING)
2250 static RenderObject::BlockContentHeightType includeNonFixedHeight(const RenderObject& renderer)
2251 {
2252     const RenderStyle& style = renderer.style();
2253     if (style.height().type() == Fixed) {
2254         if (is<RenderBlock>(renderer)) {
2255             // For fixed height styles, if the overflow size of the element spills out of the specified
2256             // height, assume we can apply text auto-sizing.
2257             if (style.overflowY() == OVISIBLE
2258                 && style.height().value() < downcast<RenderBlock>(renderer).layoutOverflowRect().maxY())
2259                 return RenderObject::OverflowHeight;
2260         }
2261         return RenderObject::FixedHeight;
2262     }
2263     return RenderObject::FlexibleHeight;
2264 }
2265
2266 void RenderElement::adjustComputedFontSizesOnBlocks(float size, float visibleWidth)
2267 {
2268     Document* document = view().frameView().frame().document();
2269     if (!document)
2270         return;
2271
2272     Vector<int> depthStack;
2273     int currentDepth = 0;
2274     int newFixedDepth = 0;
2275
2276     // We don't apply autosizing to nodes with fixed height normally.
2277     // But we apply it to nodes which are located deep enough
2278     // (nesting depth is greater than some const) inside of a parent block
2279     // which has fixed height but its content overflows intentionally.
2280     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2281         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2282             depthStack.remove(depthStack.size() - 1);
2283         if (newFixedDepth)
2284             depthStack.append(newFixedDepth);
2285
2286         int stackSize = depthStack.size();
2287         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2288             downcast<RenderBlockFlow>(*descendent).adjustComputedFontSizes(size, visibleWidth);
2289         newFixedDepth = 0;
2290     }
2291
2292     // Remove style from auto-sizing table that are no longer valid.
2293     document->updateAutoSizedNodes();
2294 }
2295
2296 void RenderElement::resetTextAutosizing()
2297 {
2298     Document* document = view().frameView().frame().document();
2299     if (!document)
2300         return;
2301
2302     LOG(TextAutosizing, "RenderElement::resetTextAutosizing()");
2303
2304     document->clearAutoSizedNodes();
2305
2306     Vector<int> depthStack;
2307     int currentDepth = 0;
2308     int newFixedDepth = 0;
2309
2310     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2311         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2312             depthStack.remove(depthStack.size() - 1);
2313         if (newFixedDepth)
2314             depthStack.append(newFixedDepth);
2315
2316         int stackSize = depthStack.size();
2317         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2318             downcast<RenderBlockFlow>(*descendent).resetComputedFontSize();
2319         newFixedDepth = 0;
2320     }
2321 }
2322 #endif // ENABLE(TEXT_AUTOSIZING)
2323
2324 }