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