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